HOW TO:寫入文字檔 (C++/CLI)
下列程式碼範例會示範如何使用 StreamWriter 類別建立文字檔,並將文字寫入檔案,而該類別是在 System.IO 命名空間中定義。StreamWriter 建構函式會使用所要建立之檔案的名稱。如果檔案已存在,它就會被覆寫 (除非您傳遞 True 做為第二個 StringWriter 建構函式引數)。
接著,這個檔案會使用 Write 和 WriteLine 函式存檔。
範例
// 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;
}