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++斐波纳契数列