zl程序教程

您现在的位置是:首页 >  后端

当前栏目

C++文本文件的读取和写入

C++ 读取 写入 文本文件
2023-06-13 09:11:55 时间
使用文件流对象打开文件后,文件就成为一个输入流或输出流。对于文本文件,可以使用 cin、cout 读写。

在《C++文件类(文件流类)》一节中提到,流的成员函数和流操纵算子同样适用于文件流,因为 ifstream 是 istream 的派生类,ofstream 是 ostream 的派生类,fstream 是 iostream 的派生类,而 iostream 又是从 istream 和 ostream 共同派生而来的。

例题:编写一个程序,将文件 in.txt 中的整数排序后输出到 out.txt。例如,若 in.txt 的内容为:
1 234 9 45
6 879

则执行本程序后,生成的 out.txt 的内容为:
1 6 9 45 234 879

假设 in.txt 中的整数不超过 1000 个。

示例程序如下:


#include iostream 

#include fstream 

#include cstdlib //qsort在此头文件中声明

using namespace std;

const int MAX_NUM = 1000;

int a[MAX_NUM]; //存放文件中读入的整数

int MyCompare(const void * e1, const void * e2)

{ //用于qsort的比较函数

 return *((int *)e1) - *((int *)e2);

int main()

 int total = 0;//读入的整数个数

 ifstream srcFile( in.txt ,ios::in); //以文本模式打开in.txt备读

 if(!srcFile) { //打开失败

 cout error opening source file. endl;

 return 0;

 ofstream destFile( out.txt ,ios::out); //以文本模式打开out.txt备写

 if(!destFile) {

 srcFile.close(); //程序结束前不能忘记关闭以前打开过的文件

 cout error opening destination file. endl;

 return 0;

 int x; 

 while(srcFile x) //可以像用cin那样用ifstream对象

 a[total++] = x;

 qsort(a,total,sizeof(int),MyCompare); //排序

 for(int i = 0;i total; ++i)

 destFile a[i] //可以像用cout那样用ofstream对象

 destFile.close();

 srcFile.close();

 return 0;

}

程序中如果用二进制方式打开文件,结果毫无区别。

第 21 行是初学者容易忽略的。程序结束前不要忘记关闭以前打开过的文件。

21577.html

chtml