c++中的文件操作

file manipulation in c++

本文关键字:操作 文件 c++      更新时间:2023-10-16

我将python中的此代码转换为c++:

content = file(filename, "rb").read()

这是c++中的代码:

ifstream file;
file.open(filename, fstream::binary);
file.seekg (0, ios::end);
long fileLength = file.tellg();
file.seekg(0, ios_base::beg);
char *content = new char[fileLength];
file.read(content, fileLength);

当我运行python代码时,我在内容中得到一个长字符串(500个字符~),而c++代码只返回4个字符。

有什么建议吗?

感谢

读取整个文件的最简单方法是:

std::string content(
    std::istreambuf_iterator<char>(std::ifstream(filename, std::fstream::binary).rdbuf()),
    std::istreambuf_iterator<char>());