2008年11月28日星期五

[2008.11.28] 在 C++ 中說難不難的檔案輸出入處理

在 C++ 中,檔案的輸出入處理主要是利用 ifstream 與 ofstream 來完成。下列的程式可以複製一個文字檔案到另外一個:

#include <iostream>
#include <fstream>

#define OUT "_OUT"

using namespace std;

int main()
{
 string fn;
 string buff("");
 cout << "Open File Name: " ;
 cin >> fn;

 //
 // 第一步:開啟輸入用的文字檔讀取。
 //
 // ifstream::in 用來標示此檔案是用來讀的。
 //

 ifstream ifn(fn.c_str(), ifstream::in);

 if (!ifn)
 {
  cerr << "Unable to open the INPUT file: " << fn << "." << endl;
  return -1;
 } else
 {
  string lines;
  int ln = 0;

  //
  // getline 可以讀『一行』文字並存到字串。
  //
  while (getline(ifn, lines))
  {
   ++ln;
   buff += lines;

   //
   // getline 不會包括最後的換行字元!
   //
   buff += "\n";
  }

  //
  // 輸入串流使用完之後要關閉。
  //
  ifn.close();
  ifn.clear();

  cout << buff << endl;
  cout << "======== Totally " << ln << " lines. ==========" << endl;

  string fn_out = fn + OUT;

  //
  // 第二步:開啟輸出用的檔案寫入。
  //
  // ofstream::in 用來標示此檔案是用來寫入的。
  //
  ofstream ofn(fn_out.c_str(), ofstream::out);

  if (!ofn)
  {
   cerr << "Unable to open the OUTPUT file: " << fn_out << "." << endl;
   return -2;
  } else
  {

   //
   // ofstream 中的 write 方法
   // 將一個特定大小的 C String 寫入串流。
   //
   ofn.write(buff.c_str(), buff.size());

   //
   // 輸出串流使用完之後要關閉。
   //
   ofn.close();
   ofn.clear();
   return 0;
  }
 }
}

看起來其實很簡單,跟 Java 的 Reader / Writer 差不多,不過要注意的是,『檔案的存在與否』在 ofstream 中是沒有處理的,因此不論檔案有沒有存在,都會開啟 ofstream。另外一個看來得研究的地方,就是『二進位』的東西要怎麼讀寫啊 ...... = =+ 再研究看看,下次待續囉。

Edited by Deleted at 14:20, 2008.11.28.

0 意見:

張貼意見