📜  C++文件和流

📅  最后修改于: 2020-10-16 07:17:44             🧑  作者: Mango

C++文件和流

在C++编程中,我们使用iostream标准库,它提供了cin和cout方法,分别用于从输入读取和写入到输出。

要从文件中读取和写入文件,我们使用称为fstream的标准C++库。让我们看看在fstream库中定义的数据类型是:

Data Type Description
fstream It is used to create files, write information to files, and read information from files.
ifstream It is used to read information from files.
ofstream It is used to create files and write information to the files.

C++ FileStream示例:写入文件

让我们来看一个使用C++ FileStream编程写入文本文件testout.txt的简单示例。

#include 
#include 
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 
#include 
using namespace std;
int main () {
  string srg;
  ifstream filestream("testout.txt");
  if (filestream.is_open())
  {
    while ( getline (filestream,srg) )
    {
      cout << srg <

注意:在运行代码之前,需要创建一个名为“ testout.txt”的文本文件,并且在下面给出文本文件的内容:欢迎使用javaTpoint。 C++教程。

输出:

Welcome to javaTpoint.
C++ Tutorial.

C++读写示例

让我们看一个简单的示例,将数据写入文本文件testout.txt,然后使用C++ FileStream编程从文件中读取数据。

#include 
#include 
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: Nakul Jain    
Please Enter your age: 22  
 Reading from a text file:   Nakul Jain  
 22