如何:编写文本文件 (C++/CLI)

下面的代码示例演示如何创建一个文本文件并使用 StreamWriter 类向其写入文本,该类在 System.IO 命名空间中定义。 StreamWriter 构造函数获取要创建的文件的名称。 如果存在,则覆盖该文件(除非向第二个 StringWriter 构造函数参数传递了 True)。

然后使用 WriteWriteLine 函数填充该文件。

示例

// text_write.cpp
// compile with: /clr
using namespace System;
using namespace System::IO;

int main() 
{
   String^ fileName = "textfile.txt";

   StreamWriter^ sw = gcnew StreamWriter(fileName);
   sw->WriteLine("A text file is born!");
   sw->Write("You can use WriteLine");
   sw->WriteLine("...or just Write");
   sw->WriteLine("and do {0} output too.", "formatted");
   sw->WriteLine("You can also send non-text objects:");
   sw->WriteLine(DateTime::Now);
   sw->Close();
   Console::WriteLine("a new file ('{0}') has been written", fileName);

   return 0;
}

请参见

其他资源

文件和流 I/O

编程在Visual C++的.NET