在我的桌面上有 .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/