C ++将文件的所有字节都保存到char数组中? [英] C++ Get all bytes of a file in to a char array?

查看:300
本文介绍了C ++将文件的所有字节都保存到char数组中?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

给出:

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

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

How do I read the chars of the file in to the above buffer? I have been looking around online but none of the answers seem to work. They all wish to call getline().

推荐答案

在大多数情况下,关于 getline ,但是当您要抓取文件作为流您想要的字节ifstream :: read

Most of the time they are right about getline, but when you want to grab the file 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);

ifstream :: seekg

ifstream :: tellg

注意: seekg tell 以获取文件的大小属于通常有效的类别。这不能保证。 tellg 仅保证可以用于返回特定点的数字。也就是说,

NOTE: seekg and tellg to get the size of the file falls into the category of "usually works". This is not guaranteed. tellg only promises a number that can be used to return to a particular point. That said,

注意:该文件未以二进制模式打开。可能会有一些幕后的字符翻译,例如Windows新行 \r\n 转换为 \n 由C ++使用。 length 可以大于最终放置在 buffer 中的字符数。

Note: The file was not opened in binary mode. There can be some behind-the-scenes character translations, for example the Windows newline of \r\n being converted to the \n used by C++. length can be greater than the number of characters ultimately placed in buffer.

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.

如果循环缓冲读取,直到耗尽整个文件,您将需要一些其他的聪明才智。

If you're looping on buffered reads until you consume the whole file you'll want some extra smarts to catch that.

如果您想一次读取整个文件并且可以使用可调整大小的缓冲区,请按照Remy Lebeau的答案中的建议进行操作。

If you want to read the whole file in one shot and can afford to use resizable buffers, take the advice in Remy Lebeau's answer.

这篇关于C ++将文件的所有字节都保存到char数组中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆