本文涉及了文件流fstream的几种常用的读写操作
#include <iostream>
#include <fstream>
#include <string>
#include <stdlib.h>
using namespace std;
int main(){
fstream file;
//写操作
file.open("file_test.txt",ios::out);
if(!file.is_open()){ //检查文件是否已打开
cout<<"file open fail!"<<endl;
return 0;
}
file<<"File Write:"<<endl;
//预备数据
char str[][0xFF]={{"first"},{"second"},{"third"}};
int data[]={1,2,3};
// cout<<"sizeof(str)="<<sizeof(str)<<endl;
// cout<<"sizeof(str[0])"<<sizeof(str[0])<<endl;
// for(int i=0;i<sizeof(str)/sizeof(str[0]);i++){cout<<str[i]<<endl;}
//第一种:使用<<运算符
file<<"Type 1(<<):"<<endl;
for(int i=0;i<sizeof(str)/sizeof(str[0]);i++){
file<<str[i]<<"=";
file<<data[i]<<endl;
}
file<<endl;
file.close();
//第二种:使用fstream的成员函数
file.open("file_test.txt",ios::app);
file<<"Type 2(write):"<<endl;
for(int i=0;i<sizeof(str)/sizeof(str[0]);i++){
string deng="=";
string t=str[i]+deng+to_string(data[i])+"\n";
// cout<<"“ "<<t<<" ”:"<<endl<<"t.size()="<<t.size()<<endl<<"sizeof(t)="<<sizeof(t)<<endl<<endl;
// sizeof()括号内无所谓值,只在乎类型,同一类型的传参,sizeof的结果相同,均为类型所占字节数
file.write(t.c_str(),t.size());
}
file.close();
//读操作
file.open("file_test.txt",ios::in);
if(!file.is_open()){
return 0;
}
//第一种:使用>>运算符
cout<<">>file.tellg():"<<file.tellg()<<endl;
while(!file.eof()){
string str;
file>>str;
cout<<str<<endl;
}
cout<<">>file.eof():"<<file.eof()<<endl;
cout<<">>file.tellg():"<<file.tellg()<<endl;
//第二种:使用fstream的成员函数
file.clear();//消除eof状态
file.seekg(0,file.beg);
cout<<endl<<"get():"<<endl;
cout<<"get::file.tellg():"<<file.tellg()<<endl;
while(!file.eof()){
char t;
if(!file.get(t)){//非常重要!!!解决了由于eof()函数返回值滞后,而导致最后一个字符重复读取的error!
break;
}
cout<<t<<endl;
}
cout<<"end::get::file.tellg():"<<file.tellg()<<endl;
file.clear();
file.seekp(0,file.beg);
cout<<endl<<"getline():"<<endl;
file.seekg(0);
cout<<"file.tellg():"<<file.tellg()<<endl;
while(!file.eof()){
string str;
if(!getline(file,str))
{
break;
}
// getline(file,str);
cout<<str<<endl;
}
return 0;
}