Search code examples
c++fstream

C++ - std::fstream read() does not read full file


I would like to create a MIDI interpreter to use in a bigger project, but I'm currently facing a huge problem : It seems that in some cases, my file is not completely read, and so I don't have the whole data I need... For example, I have a file that is around 30 000 bytes long, and the fstream::read() function reads only around 3000 of them...

My code is below, if someone may have an idea...

I haven't found any similar question, but if there are any, please tell me.

    std::ifstream file;
    file.open("Songs/" + filename + ".mid");
    if (!file.is_open())
    {
        std::cerr << "Failed to open file" << std::endl;
        return;
    }
    std::vector<unsigned char> fileData;

    while (file.read((char *)&c, 1))
    {
        fileData.push_back(c);
    }
    file.close();

Solution

  • By default, file streams use "in + out" mode to open a filestream for a text file. Try to combine exactly "in" (as you read from the file) and "binary" (as your file is not a plain text), something like this:

    std::ifstream file;
    file.open("Songs/" + filename + ".mid", std::ios_base::in | std::ios_base::binary);
    if (!file.is_open())
    {
        std::cerr << "Failed to open file" << std::endl;
        return;
    }
    std::vector<unsigned char> fileData;
    
    while (file.read((char *)&c, 1))
    {
        fileData.push_back(c);
    }
    file.close();