【C++ 檔案處理 #1】C 語法的檔案讀取 istream (header: fstream, std::ifstream), 與 iostream 直接比較

前言

開頭趁大家注意力還在的時候,
我們先把最容易混淆的幾個 (我自己都非常經常混淆的),
趕快整理起來。

我們今天要介紹的檔案讀取,

  • 是 C 語言底下的 istream 類別 (class),
  • std::ifstream,是他實際使用的名稱。
  • fstream,則是他的 header。
#include <fstream>

另外還有一個會一起來搗亂的是 iostream,

在此我們使用,是為了 cout 使用,
不要看名字很像就混在一起了,例如我 Q_Q

#include <iostream>

範例程式碼

讓我們直接來看範例程式碼吧!

// read a file into memory
#include <iostream>     // std::cout
#include <fstream>      // std::ifstream

using namespace std;

int main () {

  std::ifstream is ("test.txt", std::ifstream::binary);
  if (is) {
    // get length of file:
    is.seekg (0, is.end); // set position to end
    int length = is.tellg();  // get length
    is.seekg (0, is.beg);  // set position to start

    char * buffer = new char [length];

    std::cout << "Reading " << length << " characters... ";
    // read data as a block:
    is.read (buffer, length);

    if (is)
      std::cout << "all characters read successfully." << endl;
    else
      std::cout << "error: only " << is.gcount() << " could be read" << endl;
    is.close();

    // ...buffer contains the entire file...
    cout << buffer << endl;
    cout << *buffer << endl; // first word
    cout << *(buffer+1) << endl; // second word
    cout << buffer[1] << endl; // second word


    delete[] buffer;
  }
  return 0;
}

結果

Reference