Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ reading text file by blocks

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.

like image 264
iwtu Avatar asked Nov 01 '25 03:11

iwtu


1 Answers

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?

like image 142
mathematician1975 Avatar answered Nov 03 '25 17:11

mathematician1975



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!