C.C++把整个文件内容读进一个buffer中

时间:2023-03-09 14:39:47
C.C++把整个文件内容读进一个buffer中

原创文章,未经本人允许禁止转载。

//C方式, 调用的函数繁多
//fopen,fseek,ftell,fseek,malloc,fread,fclose,free.
void foo()
{
FILE* fp=fopen(sFileName,"rb");
fseek(fp,,SEEK_END);
int len = ftell(fp);
fseek(fp,,SEEK_SET);
char* s = (char*)malloc(len);
fread(s,,len,fp);
fclose(fp);
fwrite(s,,len,stdout);//output
free(s);
}
//C++方式,易懂
void foo()
{
ifstream fs(sFileName.c_str(),ios::binary);
stringstream ss ;
ss << fs.rdbuf();
fs.close();
string str = ss.str();//read into string
}
//C++方式,高大上
//string的构造用了一个模版函数
void foo()
{
std::ifstream ifs(sFileName.c_str());
std::string str((std::istreambuf_iterator<char>(ifs)), std::istreambuf_iterator<char>());
ifs.close();
}

原创文章,未经本人允许禁止转载。