#include
#include
#include
std::size_t getFileSize1(const std::string& filename)
{
std::ifstream in{filename};
if(!in.is_open()){
return -1;
}
std::filebuf* pbuf = in.rdbuf();
std::size_t size = pbuf->pubseekoff (0,in.end,in.in);
in.close();
return size;
}
long getFileSize(const std::string& filename)
{
std::ifstream in{filename};
if(!in.is_open()){
return -1;
}
std::streampos begin = in.tellg();
in.seekg(0,std::ios::end);
auto end = in.tellg();
in.close();
return (end-begin);
}
c语言
long cgetFileSize(const std::string& filename)
{
FILE* fp = fopen(filename.c_str(),"r");
if(!fp){
return -1;
}
fseek(fp,0,SEEK_END);
long lSize = ftell(fp);
fclose(fp);
return lSize;
}
bool readAll(const std::string& filename,std::string& out)
{
std::ifstream in{filename};
if(!in.is_open()){
return false;
}
std::istreambuf_iterator<char> begin{in},end;
out.append(begin,end);
in.close();
return true;
}
https://cplusplus.com/reference/fstream/ifstream/rdbuf/
char* readAll(const std::string& filename)
{
std::ifstream in{filename};
if(!in.is_open()){
return nullptr;
}
std::streampos begin = in.tellg();
in.seekg(0,std::ios::end);
auto end = in.tellg();
auto nFilesize = (end-begin);
char* buf =new(std::nothrow) char[nFilesize];
if(!buf){
return nullptr;
}
in.seekg(0,std::ios::beg);
in.read(buf,nFilesize);
in.close();
return buf;
}
char* readAll1(const std::string& filename)
{
std::ifstream in{filename};
if(!in.is_open()){
return nullptr;
}
std::filebuf* pbuf = in.rdbuf();
// get file size using buffer's members
std::size_t size = pbuf->pubseekoff (0,in.end,in.in);
pbuf->pubseekpos (0,in.in);
// allocate memory to contain file data
char* buffer=new(std::nothrow) char[size];
if(!buffer){
return nullptr;
}
// get file data
pbuf->sgetn (buffer,size);
// write content to stdout
std::cout.write (buffer,size);
in.close();
return buffer;
}
void readChar(const std::string& filename,bool (*cb)(char))
{
std::ifstream in{filename};
if(!in.is_open()){
return;
}
while(in.good()){
char ch = in.get();
if(cb(ch)){
break;
}
};
in.close();
}
readChar("main.cpp",[](char ch)->bool{
std::cout<<ch;
return false;
});
void readLine(const std::string& filename,bool (*cb)(char*))
{
std::ifstream in{filename};
if(!in.is_open()){
return;
}
char* str = new(std::nothrow) char[1024];
while(in.good()){
in.getline(str,1024);
if(cb(str)){
break;
}
};
delete []str;
in.close();
}
输出单个单词,即以空格为分割
void readString(const std::string& filename,bool (*cb)(const std::string& str))
{
std::ifstream in{filename};
if(!in.is_open()){
return;
}
std::string str;
while(in >> str){
if(cb(str)){
break;
}
};
in.close();
}
void readInt(const std::string& filename,bool (*cb)(int value))
{
std::ifstream in{filename};
if(!in.is_open()){
return;
}
int value;
while(in >> value){
if(cb(value)){
break;
}
};
in.close();
}
文件内容
123 456
读取
readInt("D:\\1.txt",[](int value)->bool{
std::cout<<value<<std::endl;
return false;
});
输出
123
456