将文件读入缓冲区

时间:2018-04-21 20:25:04

标签: c++ file buffer ifstream

我有一点问题,我无法弄清楚 我试图将文件读入缓冲区, 我的问题是,有时它会在文本末尾添加一个随机字符。 (有时?和abs等)。所以我想知道为什么会这样。我还没有找到任何解决方案。问题是随机发生的,而不是每次我都读到文件。

    static char text[1024 * 16];
    std::ifstream File(FilePath, std::ios::in | std::ios::out | std::ios::binary | std::ios::ate);
    std::streamsize Size = File.tellg();
    File.seekg(0, std::ios::beg);
    char *string = new char[Size + 1];
    if (File.is_open()) 
    {
         File.read(string, Size);
         memset(text, 0, sizeof(text));
         snprintf(text, sizeof(text), "%s", string);

    }
    File.close();
    delete[] string;

1 个答案:

答案 0 :(得分:1)

请注意,read()不附加空终止符,它只是一个原始二进制读取。换句话说,数据不是字符串,它是一个字节数组。您可能正在尝试将其打印出来或其他东西,它只是继续前进,直到它看到一个空终止符,可能进入未初始化的内存。您应该手动分配大小+ 1并在末尾添加空终止符。

几种风格的注释:不建议使用变量名,例如" File"或"尺寸"。它是合法但不好的做法,您可以查看一些流行的风格指南以获取更多信息(GoogleLLVM

其次,我会尝试使用std :: string而不是手动分配内存,即使在堆栈上也是如此。查看reserve()data()

这是一个使用std :: string的更简洁的例子。更具可读性,更易于编写,效率更高。

const char *somefile = "main.cpp";
std::ifstream fh(somefile, std::ios::in | std::ios::out | std::ios::binary |
                               std::ios::ate);
const size_t sz = fh.tellg();
if (sz <= 0) {
    // error handling here
}
fh.seekg(0, std::ios::beg);
// Initalizes a std::string with length sz, filled with null
std::string str = std::string(sz, '\0');
if (fh.is_open())
    fh.read(&str[0], sz);
fh.close();
std::cout << str << "[EOF]\n";
相关问题