C++ 读取一个文件
2021-04-21 本文已影响0人
一点墨汁
// 获取文件大小
long getFileSize(const char * const & filePath) {
FILE *fp = fopen(filePath, "rb");
if (fp == nullptr) {
return -1;
}
fseek(fp, 0, SEEK_END);
long fileSize = ftell(fp);
fclose(fp);
return fileSize;
}
int main() {
const char *filePath = "log.txt";
int size = getFileSize(filePath);
// 不要在栈上申请空间,否则可能会导致栈溢出!
char *buf = new char[size];
memset(buf, 0, size);
fstream file;
file.open(filePath, ios::binary|ios::in);
if(!file.is_open()){
std::cout<<"open fail"<<std::endl;
return 0;
}
file.read(buf, size);
cout<<buf<<endl;
delete[] buf;
file.close();
return 0;
}