cpp 专题
专题目录
您的位置:cpp > cpp 专题 > C++文件和流
C++文件和流
作者:--    发布时间:2019-11-20

在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 h3.com.
c++ tutorial.

执行上面代码输出结果如下 -

welcome to h3.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

网站声明:
本站部分内容来自网络,如您发现本站内容
侵害到您的利益,请联系本站管理员处理。
联系站长
373515719@qq.com
关于本站:
编程参考手册