C++ 檔案讀取



C++ 中的檔案 I/O(輸入/輸出)是讀取和寫入檔案的過程。C++ 透過標準庫和 <fstream> 標頭檔案提供了用於處理檔案的功能。 檔案 I/O 允許程式持久化資料,與外部資源互動,以及儲存/檢索超出程式執行範圍的資訊。

檔案流型別

有三種主要型別的檔案流,每種與不同的操作相關聯:

  • ifstream(輸入檔案流) - 用於從檔案讀取資料。
  • ofstream(輸出檔案流) - 用於將資料寫入檔案。
  • fstream(檔案流) - 用於對檔案進行輸入和輸出操作。它結合了 ifstream 和 ofstream 的功能。

檔案 I/O 的基本步驟

以下是檔案 I/O 的基本步驟:

開啟檔案

在讀取或寫入檔案之前,必須使用其中一個檔案流類開啟它。如果檔案成功開啟,程式將繼續進行 I/O 操作。

執行檔案操作

可以使用適當的方法讀取或寫入檔案。

關閉檔案

檔案操作完成後,應關閉檔案以確保所有資料都被重新整理並且檔案被正確釋放。

使用 ifstream 讀取(流提取運算子)

使用流提取運算子(>>)是從檔案中讀取資料的最簡單方法。此運算子從檔案讀取格式化資料,類似於從標準輸入讀取資料的方式。

示例

以下是使用 ifstream 讀取的示例:

#include <fstream>
#include <iostream>
#include <string>

int main() {
   std::ifstream inputFile("example.txt");  // Open the file for reading
   if (!inputFile) {
      std::cerr << "Error opening file!" << std::endl;
      return 1;
   }

   std::string word;
   while (inputFile >> word) {  // Reads until a whitespace is encountered
      std::cout << word << std::endl;  // Print each word from the file
   }

   inputFile.close();  // Close the file when done
   return 0;
}

這裡,>> 運算子逐個讀取單詞,在空白字元(空格、換行符等)處停止。

但它不處理讀取文字行(因為它在空白字元處停止),並且對於讀取複雜的資料格式(如包含空格的行)可能很棘手。

使用 getline() 讀取行

如果要讀取整行或文字,包括步驟,可以使用 getline() 函式。此函式將從檔案中讀取字元,直到遇到換行符('\n')。

示例

以下是使用 getline() 讀取行的示例:

#include <fstream>
#include <iostream>
#include <string>

int main() {
   std::ifstream inputFile("example.txt");  // Open the file for reading
   if (!inputFile) {
      std::cerr << "Error opening file!" << std::endl;
      return 1;
   }

   std::string line;
      while (std::getline(inputFile, line)) {  // Read a full line of text
      std::cout << line << std::endl;  // Output the line to the console
   }

   inputFile.close();  // Close the file when done
   return 0;
}

讀取二進位制檔案(使用 read())

上面討論的方法適用於文字檔案,對於二進位制檔案,可以使用 read() 函式從檔案中讀取原始二進位制資料。

示例

以下是讀取二進位制檔案(使用 read())的示例:

#include <iostream>
#include <fstream>

int main() {
   std::ifstream file("example.bin", std::ios::binary);

   // Check if the file was successfully opened
   if (!file) {
      std::cerr << "Error opening file!" << std::endl;
      return 1;
   }

   // Get the length of the file
   file.seekg(0, std::ios::end);
   std::streamsize size = file.tellg();
   file.seekg(0, std::ios::beg);

   // Read the entire file content into a buffer
   char* buffer = new char[size];
   file.read(buffer, size);

   // Print raw data (optional, for demonstration)
   for (std::streamsize i = 0; i < size; ++i) {
      std::cout << std::hex << (0xFF & buffer[i]) << " ";  // Print byte in hex
   }

   delete[] buffer;
   file.close();
   return 0;
}

處理檔案 I/O 中的錯誤

處理錯誤對於確保程式在檔案不可用、無法開啟或在讀取/寫入過程中發生意外情況時能夠正確執行非常重要。

使用 fail()eof()good() 檢查錯誤。

C++ 提供了 ifstream/ofstream 物件的幾個成員函式來檢查各種條件。

  • fail():檢查 I/O 期間是否發生不可恢復的錯誤。
  • eof():檢查是否到達檔案末尾 (EOF)。
  • good():如果未發生錯誤,則返回 true。

處理檔案末尾 (EOF)

從檔案讀取時,務必處理到達檔案末尾的情況。標準方法是使用 eof()std::getline() 運算子,它們會在到達檔案末尾時自動停止。

優雅地處理 I/O 錯誤

在檔案操作期間,應檢查 fail() 或 bad() 狀態以檢測意外檔案末尾或資料損壞等錯誤。

廣告