C++ fstream文件读取操作

1.在头文件fstram中,定义了了三个类型:ifstream用来从一个给定文件中读取数据,ofstream向一个给定文件写入数据,fstream读写指定文件。

2.fstream是iostream的一个基类,所以我们也可以使用<<、>>、getline等来操作fstream

3.使用>>从文件中读取数据,和从控制cin>>类似,这种读取方式在遇到空格时就结束一次读取了。

int main(int argc,char *argv[]){

std::fstream in("test.txt",std::fstream::in);//std::fstream::in表示以只读方式打开

bool bl = in.is_open();//判读test.txt文件是否存在,即是否成功打开

cout<<bl<<endl;

string str;

while(in>>str){//从流中读取数据

cout<<str<<endl;

}

in.close();//在流使用完毕后关闭流

}

4.使用getline从fstream中独取数据

std::fstream in("test.txt",std::fstream::in);

bool bl = in.is_open();

cout<<bl<<endl;

string str;

while(std::getline( in,str)){//和上面的读取方式写法类似,只是每次是读取一整行

cout<<str<<endl;

}

in.close();

5.使用<<向文件中写入数据,如果目标文件不存在会自动创建文件,如果文件存在则原文件中的内容将会被覆盖。如果想不覆盖源文件接着在后面写入,将下面代码中的std::fstream::out模式换为std::fstream::out即可。

std::fstream out("test1.txt",std::fstream::out);//std::fstream::out表示以只写的方式打开文件

bool bl = out.is_open();

cout<<bl<<endl;

for(int i= 5;i<10;i++){

out<<i<<endl;

}

out.close();