c++ - 如何从文件中读取字节? C++

标签 c++ file

在我的桌面上有 .txt 文件。我需要将所有字节从内存读取到数组。

我尝试将文本从文件读取到字符串,然后使用 memcpy() 从字符串读取字节,但我认为这是不正确的。

谢谢。

ifstream File("C:\\Users\\Flone\\Desktop\\ass.txt");
string file_text;
//start to read TEXT file (look end below):
char word_buffer[30];
for (int i = 0; i < 30; i++)
{
    word_buffer[i] = NULL;
}
while (File.eof() == false)
{
    File >> word_buffer;
    for (int i = 0; i < 30; i++)
    {
        if (word_buffer[i] != NULL)
        {
            file_text += word_buffer[i];
        }
    }
    if (File.eof()==false) file_text += " ";
    for (int i = 0; i < 30; i++)
    {
        word_buffer[i] = NULL;
    }
}
File.close();
//end read TEXT file.
cout << file_text << endl;

它有效,但我正在从我的字符串而不是文件中读取字节,或者它是相同的吗?

最佳答案

使用 vector 的小例子

#include <fstream>
#include <iterator>
#include <vector>

从文件中读取字节到 vector 中

    std::ifstream input("d:\\testinput.txt", std::ios::binary);

    std::vector<char> bytes(
         (std::istreambuf_iterator<char>(input)),
         (std::istreambuf_iterator<char>()));

    input.close();

关于c++ - 如何从文件中读取字节? C++,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50315742/

相关文章:

带有表达式的 C++ 初始化列表

c++ - 在类中定义变量

c++ - 为什么对函数内部的指针所做的更改在函数外部不可见?

python - 在 python 中获得相当于 "find ."的最简单方法?

python - 打印到文件的倒数第二行

c++ - C++中的头文件

c - 使用C查找文件权限

c++ - 传递给新线程的结构有错误的值

c++ - 递归划分图像并并行处理

java - 在 zip 存档中使用 Unicode 字符作为文件名