HOW TO:讀取文字檔 (C++/CLI)

下列程式碼範例會示範如何開啟並讀取文字檔案,一次一行。 這項作業使用在 System.IO 命名空間中定義的 StreamReader 類別 (Class) 來完成。 範例會使用這個類別的執行個體來開啟文字檔案,然後使用 StreamReader.ReadLine 方法來擷取每一行。

這個程式碼可以用在任何名稱為 textfile.txt 且包含文字的檔案,或是在 HOW TO:寫入文字檔 (C++/CLI)中產生的檔案。

範例

// text_read.cpp
// compile with: /clr
#using<system.dll>
using namespace System;
using namespace System::IO;

int main()
{
   String^ fileName = "textfile.txt";
   try 
   {
      Console::WriteLine("trying to open file {0}...", fileName);
      StreamReader^ din = File::OpenText(fileName);

      String^ str;
      int count = 0;
      while ((str = din->ReadLine()) != nullptr) 
      {
         count++;
         Console::WriteLine("line {0}: {1}", count, str );
      }
   }
   catch (Exception^ e)
   {
      if (dynamic_cast<FileNotFoundException^>(e))
         Console::WriteLine("file '{0}' not found", fileName);
      else
         Console::WriteLine("problem reading file '{0}'", fileName);
   }

   return 0;
}

請參閱

其他資源

檔案和資料流 I/O

.NET 程式設計指南