C++ 文件和流

C++ 文件和流 首页 / C++入门教程 / C++ 文件和流

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

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

数据类型 说明
fstream 它用于创建文件,将信息写入文件以及从文件读取信息。
ifstream 它用于从文件中读取信息。
ofstream 它用于创建文件并将信息写入文件。

写入文件

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

#include <iostream>
#include <fstream>
using namespace std;
int main () {
  ofstream filestream("testout.txt");
  if (filestream.is_open())
  {
    filestream << "Welcome to learnfk.\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 learnfk.
C++ Tutorial.

从文件读取

让我们看一个使用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;
}

Note: 在运行代码之前,需要创建一个名为“ testout.txt”的文本文件,文本文件的内容如下:欢迎使用learningfk。 C++教程。

输出:

Welcome to learnfk.
C++ Tutorial.

读写示例

让我们看一个简单的示例,将数据写入文本文件 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: Nakul Jain    
Please Enter your age: 22  
 Reading from a text file:   Nakul Jain  
 22

祝学习愉快!(内容编辑有误?请选中要编辑内容 -> 右键 -> 修改 -> 提交!)

技术教程推荐

Node.js开发实战 -〔杨浩〕

MongoDB高手课 -〔唐建法(TJ)〕

接口测试入门课 -〔陈磊〕

编译原理实战课 -〔宫文学〕

体验设计案例课 -〔炒炒〕

攻克视频技术 -〔李江〕

AI绘画核心技术与实战 -〔南柯〕

结构思考力 · 透过结构看思考 -〔李忠秋〕

结构会议力 -〔李忠秋〕

好记忆不如烂笔头。留下您的足迹吧 :)