簡體   English   中英

C ++將文件的所有字節放入char數組中?

[英]C++ Get all bytes of a file in to a char array?

鑒於:

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

如何將文件的字符讀入上述緩沖區? 我一直在網上四處尋找,但似乎沒有一個答案有效。 他們都希望調用 getline()。

注意:Remy Lebeau 的回答開始。 對於一般文件閱讀,這個答案涵蓋了完成這項工作的艱難方法; 它更好地滿足了這個特定詢問者的特定需求,但不一定能滿足您的需求以及 Remy 概述的std::vectorstd::istreambuf_iterator方法。


大多數情況下,他們對getline是正確的,但是當您想將文件作為字節流抓取時,您需要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()tellg()獲取文件大小屬於“通常有效”的類別。 這不能保證。 tellg()只承諾一個可用於返回特定點的數字。 那就是說...

注意:該文件不是以二進制模式打開的。 可能會有一些幕后字符翻譯,例如 Windows 換行符\r\n被轉換為 C++ 使用的\n length可以大於最終放入buffer的字符數。

2019年重新思考

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 的回答中的建議。

另一種選擇是使用std::vector作為緩沖區,然后使用std::istreambuf_iteratorstd::ifstream直接讀取到std::vector ,例如:

const std::string inputFile = "C:\\MyFile.csv";
std::ifstream infile(inputFile, std::ios_base::binary);

std::vector<char> buffer( std::istreambuf_iterator<char>(infile),
                          std::istreambuf_iterator<char>() );

或者:

const std::string inputFile = "C:\\MyFile.csv";
std::ifstream inFile(inputFile, std::ios_base::binary);

inFile.seekg(0, std::ios_base::end);
size_t length = inFile.tellg();
inFile.seekg(0, std::ios_base::beg);

std::vector<char> buffer;
buffer.reserve(length);
std::copy( std::istreambuf_iterator<char>(inFile),
           std::istreambuf_iterator<char>(),
           std::back_inserter(buffer) );

如果您使用@user4581301 的解決方案,我仍然建議使用std::vector作為緩沖區,至少:

//open file
std::ifstream infile("C:\\MyFile.csv");
std::vector<char> buffer;

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

//read file
if (length > 0) {
    buffer.resize(length);    
    infile.read(&buffer[0], length);
}

如果您關心效率(您拒絕了getline() ),那么 C 風格的mmap可能是最好的:

#include <sys/stat.h>
#include <sys/mman.h>

struct stat s;
stat(inputFile.c_str(), &s);
size_t file_size = st.st_size;

int fhand = open(inputFile);
char* file_buf = (char*)mmap(0, file_size, PROT_READ, MAP_FILE|MAP_PRIVATE, fhand, 0);
...
munmap(file_buf, file_size);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM