c++文件输入输出流
文件I/O:内存与外部文件之间的信息的传递
ifstream文件输入流/ofstream文件输出流/fstream文件输入输出流
文件模式:
in:做读操作
out:做写操作,清空流的内容,当文件不存在时,会直接创建新文件,并写如数据,当文件存在时,会清空文件流的内容
ate:文件指针偏移到文件流的末尾,配合读操作
app:写操作,只能在末尾追加写(不管文件游标在哪里,都只会在文件末尾写入)
trunc:打开文件时,清空流的内容
binary:以二进制方式打开文件
实例:
#include <iostream>
#include <string>
#include <fstream>
using std::cin;
using std::cout;
using std::endl;
using std::ifstream;
using std::string;
void test0()
{
string filename("./student.cc");
ifstream ifs(filename);
if(!ifs){
cout<<"ifstrem open file error"<<endl;
return ;
}
//打印游标位置
cout<<"current pos:"<<ifs.tellg()<<endl;
//先拿到文件的长度,偏移到文件的末尾
ifs.seekg(0,std::ios::end);//两个参数的含义
//第一个参数时偏移量正值表示相后偏移,负值表示向
//前偏移,第二个参数是基地址
size_t length=ifs.tellg();
cout<<"current pos:"<<length<<endl;
char *pbuff = new char[length+1]();
ifs.seekg(0,std::ios::beg);
ifs.read(pbuff,length);
string content(pbuff,length);
cout<<"content:"<<content<<endl;
ifs.close();
delete [] pbuff;
}
int main()
{
test0();
return 0;
}
运行结果
out流
out模式会清空流
app模式
void test1()
{
ofstream ofs("test.txt",std::ios::app);
if(!ofs){
cout<<"ofs open file error"<<endl;
return ;
}
ofs.seekp(0);//游标偏移到开头
string line = "this is a line ";
ofs<<line<<endl;//仍然会输出到末尾
ofs.close();
}
仍然添加到了末尾
每次获取一行文件
std::getline(ifs,line);
动态查看某一个文件中的最新内容
$tail -F 文件名