乐清做网站,西安seo网站公司,上海网站建设到诺然,骏域网络科技有限公司使用文件流对象打开文件后#xff0c;文件就成为一个输入流或输出流。对于文本文件#xff0c;可以使用 cin、cout 读写。
流的成员函数和流操纵算子同样适用于文件流#xff0c;因为 ifstream 是 istream 的派生类#xff0c;ofstream 是 ostream 的派生类#xff0c;fs…使用文件流对象打开文件后文件就成为一个输入流或输出流。对于文本文件可以使用 cin、cout 读写。
流的成员函数和流操纵算子同样适用于文件流因为 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;
}程序中如果用二进制方式打开文件结果毫无区别。
注意程序结束前不要忘记关闭以前打开过的文件。