首先,c++的文件输入输出的头文件是#include <fstream.h>
第一次看到别人代码的时候是这样的:
freopen("4.in.txt","r",stdin);
freopen("4.out.txt","w",stdout);
fclose(stdin);
fclose(stdout);
试过,这样是可行的
不过网上的貌似更具体一些
ofstream outfile("f:/f1.txt",ios::out);
if(!outfile)
{
cerr<<"open file error!"<<endl;
exit(1);
}
outfile<<"I Love You";
outfile.close();
输入与输出同理
ifstream infile("f:/f1.txt",ios::in);
函数原型:
还有文件定位
C++的文件定位分为读位置和写位置的定位,对应的成员函数是 seekg()和 seekp(),
seekg()是设置读位置,seekp()是设置写位置。
它们最通用的形式如下:
istream &seekg(streamoff offset,seek_dir origin); ostream &seekp(streamoff offset,seek_dir origin);
streamoff定义于 iostream.h 中,定义有偏移量 offset 所能取得的最大值,
seek_dir 表示移动的基准位置,是一个有以下值的枚举:
ios::beg: 文件开头
ios::cur: 文件当前位置
ios::end: 文件结尾