本文主要介绍使用fstream流输入和输出txt文件的方法及相关注意事项。
1.使用fstream写入到txt文件中
使用fstream将相关信息写入到txt文件中,因为fstream既能读又能写,所以在打开txt文件时需要指明对其进行的操作。
例如:fstream writefile;writefile.open("a.txt",ios::out|ios::app)//除了使用open方式打开外也可以使用构造函数方式打开txt文件,fstream writefile("a.txt",ios::out|ios::app);
关于文件的打开方式说明如下:
in:以读方式打开
out:以写方式打开
app:每次写操作均定位到文件末尾(若想每次写数据都在上一条数据之后写则需要设置该方式,否则每次写数据都将覆盖之前的数据)
ate:打开文件后立即定位到文件末尾(若想每次读数据都按照从头到尾读出txt文件中全部内容,则不定义该模式,若定义该模式只能读出最后一行数据)
trunc:截断文件(只有在写操作的时候才用,没用过)
binary:以二进制方式进行IO(以二进制形式进行文件的读写操作,默认是以文本形式)
在打开文件之后(默认为文件存在打开,文件不存在新建一个),可以使用writefile.write()或writefile<<"" 写入文件,切记在用完后一定要记得关闭流,writefile.close();
代码示例:
fstream out;
out.open("./liwei.txt",ios::out|ios::app);
pr.writeToFile(out);
void Personal::writeToFile(fstream& out) {
out.write(SSN,9);
out.write(name,nameLen);
out.write(city,cityLen);
out.write(reinterpret_cast<const char*>(&year),sizeof(int));
out.write(reinterpret_cast<const char*>(&salary),sizeof(long));
}
2.使用fstream从txt文件中读
使用fstream读文件的时候,后面不要加ios::ate 否则只能读取最后一行数据不能全部读取文件中数据;例如:fstream readfile;readfile.open("a.txt",ios::in) //同样可以利用构造函数打开,这里不再赘述。
读取文件位置操作:
seekg(绝对位置); //绝对移动,通过seekg(绝对位置)函数可以设置从文件哪个位置开始读,streampos为位置类型名 示例:streampos curpos; seekg(curpos);
seekg(偏移量,相对位置); //相对操作,偏移量可正可负,0表示不偏移,正表示在相对位置往后移动偏移量,负数表示往前移动偏移量;
相对位置有三种情况:ios::beg ios::cur ios::end seekg(0,ios::end)//表示定位到文件尾 不偏移,seekg(5,ios::beg)//定位到文件头往后偏移5字节
tellg(); //返回当前指针位置
seekp(绝对位置); //绝对移动
seekp(偏移量,相对位置); //相对操作
tellp(); //返回当前指针位置
ios::cur = 1 //相对于当前位置
ios::end = 2 //相对于文件尾
读取文件代码示例:
pr.curpos=pr.initpos=input_file.tellg();
while (input_file.peek()!=EOF)//!input_file.eof()此方法最后一行数据会重复输出两次
{
//pr.readFromFile(input_file);此方法也行
pr.curpos=pr.readFromFilePos(input_file,pr.curpos,pr.initpos);
cout<<pr<<endl;
}
void Personal::readFromFile(fstream& in) { in.read(SSN,9); in.read(name,nameLen); in.read(city,cityLen); in.read(reinterpret_cast<char*>(&year),sizeof(int)); in.read(reinterpret_cast<char*>(&salary),sizeof(long)); } streampos Personal::readFromFilePos(fstream& readfile,streampos cur,streampos init) { if (cur!=init) { readfile.seekg(cur); } readfile.read(SSN,9); readfile.read(name,nameLen); readfile.read(city,cityLen); readfile.read(reinterpret_cast<char*>(&year),sizeof(int)); readfile.read(reinterpret_cast<char*>(&salary),sizeof(long)); return readfile.tellg(); }