【问题标题】:How do I read bytes from file? C++如何从文件中读取字节? C++
【发布时间】:2018-05-13 11:43:19
【问题描述】:

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

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

Tnx.

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;

它可以工作,但我是从我的字符串中读取字节而不是文件,还是一样?

【问题讨论】:

标签: c++ file


【解决方案1】:

使用向量的小例子

#include <fstream>
#include <iterator>
#include <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();

【讨论】:

猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2020-09-05
  • 1970-01-01
  • 2012-01-24
  • 1970-01-01
  • 1970-01-01
  • 2012-10-05
相关资源
最近更新 更多