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

后端 未结 3 1748
礼貌的吻别
礼貌的吻别 2020-12-03 12:32

Given:

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

How do I read the chars of the file in to the above buffer? I have

3条回答
  •  温柔的废话
    2020-12-03 12:58

    Another option would be to use a std::vector for the buffer, then use a std::istreambuf_iterator to read from an std::ifstream directly into the std::vector, eg:

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

    Alternatively:

    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 buffer;
    buffer.reserve(length);
    std::copy( std::istreambuf_iterator(inFile),
               std::istreambuf_iterator(),
               std::back_inserter(buffer) );
    

    If you go with @user4581301's solution, I would still suggest using std::vector for the buffer, at least:

    //open file
    std::ifstream infile("C:\\MyFile.csv");
    std::vector 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);
    }
    

提交回复
热议问题