C++檔和流

在C++編程中,我們使用iostream標準庫,它提供了cincout方法,分別從輸入和輸出讀取流。

要從檔讀取和寫入,我們使用名稱為fstream的標準C++庫。 下麵來看看看在fstream庫中定義的數據類型是:

數據類型 描述
fstream 它用於創建檔,向檔寫入資訊以及從檔讀取資訊。
ifstream 它用於從檔讀取資訊。
ofstream 它用於創建檔以及寫入資訊到檔。

C++ FileStream示例:寫入檔

下麵來看看看使用C++ FileStream編程寫一個定稿文本檔:testout.txt的簡單例子。

#include <iostream>
#include <fstream>
using namespace std;
int main () {
  ofstream filestream("testout.txt");
  if (filestream.is_open())
  {
    filestream << "Welcome to javaTpoint.\n";
    filestream << "C++ Tutorial.\n";
    filestream.close();
  }
  else cout <<"File opening is fail.";
  return 0;
}

執行上面代碼,輸出結果如下 -

The content of a text file testout.txt is set with the data:
Welcome to javaTpoint.
C++ Tutorial.

C++ FileStream示例:從檔讀取

下麵來看看看使用C++ FileStream編程從文本檔testout.txt中讀取的簡單示例。

#include <iostream>
#include <fstream>
using namespace std;
int main () {
  string srg;
  ifstream filestream("testout.txt");
  if (filestream.is_open())
  {
    while ( getline (filestream,srg) )
    {
      cout << srg <<endl;
    }
    filestream.close();
  }
  else {
      cout << "File opening is fail."<<endl;
    }
  return 0;
}

注意:在運行代碼之前,需要創建一個名為“testout.txt”的文本檔,並且文本檔的內容如下所示:

Welcome to xuhuhu.com.
C++ Tutorial.

執行上面代碼輸出結果如下 -

Welcome to xuhuhu.com.
C++ Tutorial.

C++讀寫示例

下麵來看看一個簡單的例子,將數據寫入文本檔:testout.txt,然後使用C++ FileStream編程從檔中讀取數據。

#include <fstream>
#include <iostream>
using namespace std;
int main () {
   char input[75];
   ofstream os;
   os.open("testout.txt");
   cout <<"Writing to a text file:" << endl;
   cout << "Please Enter your name: ";
   cin.getline(input, 100);
   os << input << endl;
   cout << "Please Enter your age: ";
   cin >> input;
   cin.ignore();
   os << input << endl;
   os.close();
   ifstream is;
   string line;
   is.open("testout.txt");
   cout << "Reading from a text file:" << endl;
   while (getline (is,line))
   {
   cout << line << endl;
   }
   is.close();
   return 0;
}

執行上面代碼,得到以下結果 -

Writing to a text file:
 Please Enter your name: Nber su
Please Enter your age: 27
 Reading from a text file:   Nber su
27

上一篇: C++用戶定義異常 下一篇: C++斐波納契數列