gpt4 book ai didi

C++将文件的所有字节放入char数组?

转载 作者:太空狗 更新时间:2023-10-29 19:37:22 24 4
gpt4 key购买 nike

给定:

const string inputFile = "C:\MyFile.csv";
char buffer[10000];

如何将文件的字符读入上述缓冲区?我一直在网上四处寻找,但似乎没有一个答案有效。他们都希望调用 getline()。

最佳答案

注意:Remy Lebeau's answer 开头.对于一般的文件阅读,这个答案涵盖了完成这项工作的困难方法;它更好地满足了这个特定提问者的特定需求,但不一定能满足您的需求以及 Remy 概述的 std::vectorstd::istreambuf_iterator 方法。


大多数时候他们对 getline 是正确的,但是当你想抓取文件时 as a stream of bytes, you want ifstream::read() .

//open file
std::ifstream infile("C:\\MyFile.csv");

//get length of file
infile.seekg(0, std::ios::end);
size_t length = infile.tellg();
infile.seekg(0, std::ios::beg);

// don't overflow the buffer!
if (length > sizeof (buffer))
{
length = sizeof (buffer);
}

//read file
infile.read(buffer, length);

Docs for ifstream::seekg()

Docs for ifstream::tellg()

注意:seekg()tellg() 获取文件大小属于“通常有效”的范畴。这是无法保证的。 tellg() 只 promise 一个可用于返回特定点的数字。也就是说……

注意:文件不是以二进制模式打开的。可以有一些幕后字符转换,例如 \r\n 的 Windows 换行符被转换为 C++ 使用的 \nlength 可以大于最终放入 buffer 的字符数。

2019 反射(reflection)

size_t chars_read;
//read file
if (!(infile.read(buffer, sizeof(buffer)))) // read up to the size of the buffer
{
if (!infile.eof()) // end of file is an expected condition here and not worth
// clearing. What else are you going to read?
{
// something went wrong while reading. Find out what and handle.
}
}
chars_read = infile.gcount(); // get amount of characters really read.

如果您在读取整个文件之前循环缓冲读取,您需要一些额外的智能来捕捉它。

如果您想一次读取整个文件,并且可以使用可调整大小的缓冲区,请采纳 Remy Lebeau's answer 中的建议。 .

关于C++将文件的所有字节放入char数组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36658734/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com