C++ reading text file by blocks

14,027

You should be fine doing the following

 vector<char> buffer (1024,0);      // create vector of 1024 chars with value 0   
 fin.read(&buffer[0], buffer.size());

The elements in a vector are guaranteed to be stored contiguously, so this should work - but you should ensure that the vector is never empty. I asked a similar question here recently - check the answers to that for specific details from the standard Can I call functions that take an array/pointer argument using a std::vector instead?

Share:
14,027
iwtu
Author by

iwtu

Updated on June 04, 2022

Comments

  • iwtu
    iwtu almost 2 years

    I really didn't find a satisfied answer at google and I/O in C++ is a little bit tricky. I would like to read text file by blocks into a vector if possible. Alas, I couldn't figure out how. I am not even sure, if my infinite loop will be break in all possibilities, because I/O is tricky. So, the best way I was able to figure out is this:

    char buffer[1025]; //let's say read by 1024 char block
    buffer[1024] = '\0';
    std::fstream fin("index.xml");
    if (!fin) {
        std::cerr << "Unable to open file";        
    } else {
        while (true) {          
            fin.read(buffer, 1024);
            std::cout << buffer;
            if (fin.eof())
                break;
        }
    
    }
    

    Please, note the second line with '\0'. Is it not odd? Can I do something better? Can I read the data into the vector instead of char array? Is it appropriate to read into vector directly?

    Thanks for your answers.

    PS. Reading by chunks have sense indeed. This code is short but I am storing it in cyclic buffer.

  • iwtu
    iwtu over 11 years
    I don't see any block of data. I assume it reads whole input till the end.