如何读取和写入到文本文件中,通过使用 Visual C

如题所述

本分步指南介绍了如何读取和写入到文本文件中,通过使用 Visual c + +.net 或 Visual c + + 2005年。

要求
下面的列表概述了建议的硬件、 软件、 网络的基础结构和服务包所必需的:
Microsoft Visual c + +.net 或 Microsoft Visual c + + 2005
本文假定您熟悉下列主题:
Microsoft Visual c + +.net 或 Visual c + + 2005
读取和写入文本文件
Write a Text File (Example 1) 和 Write a Text File (Example 2) 各节介绍了如何将文本写入文件使用 StreamWriter 类。本文的 Read a Text File 部分描述如何使用 StreamReader 类来读取文本的文件。

写文本文件 (示例 1)
下面的代码使用 StreamWriter 类打开、 写入,和以关闭该文本文件。StreamReader 类以类似方式您可以将文本文件的路径名称传递给该 StreamWriter 构造函数,以自动打开该文件。WriteLine 方法写入文本文件的完整文本行。
启动 Visual Studio.net 或 Visual Studio 2005。
在 文件 菜单上指向 新建,然后单击 项目。
在 Visual Studio.net 2002 年在 项目类型 框中,单击 Visual c + + 项目,然后单击 模板 下的 托管 c + + 应用程序。

在 Visual Studio.net 2003 年在 项目类型 框中,单击 Visual c + + 项目,然后单击 模板 下的 控制台应用程序 (.NET)。

注意在可视有关 Studio 的 2005 年在 项目类型 框中,单击 Visual c + +,然后单击在 模板 下的 CLR 控制台应用程序。
在 名称 文本框中键入 Sample1,然后单击 确定。
打开 Sample1.cpp 文件。添加以下代码:
using namespace System::IO;

用下面的代码替换现有代码的 Main 函数:
try
{

//Pass the file path and file name to the StreamWriter Constructor.
StreamWriter* sw = new StreamWriter(S"C:\\Test.txt");

//Write a line of text.
sw->WriteLine(S"Hello World!!");

//Write a second line of text.
sw->WriteLine("From the StreamWriter class");

//Close the file.
sw->Close();
}
catch(Exception* e)
{
Console::WriteLine("Exception: {0}",e->Message);
}
__finally
{
Console::WriteLine("Executing finally block.");
}
return 0;

在 调试 菜单上单击 $ 开始 以编译并运行该应用程序。此代码创建的驱动器 c。 打开 Test.txt 文件在文本编辑器 (如记事本) 上名为 Test.txt 文件。Test.txt 文件中包含文本的下面两行:
Hello World!!
From the StreamWriter class
温馨提示:答案为网友推荐,仅供参考
相似回答