0

The following example code from https://en.cppreference.com/w/cpp/io/basic_istream/read uses the if-check for the returned value of ifstream::read. Is that necessary? Why?

#include <iostream>
#include <fstream>
#include <sstream>
#include <string>
#include <cstdint>
 
int main()
{
    // read() is often used for binary I/O
    std::string bin = {'\x12', '\x12', '\x12', '\x12'};
    std::istringstream raw(bin);
    std::uint32_t n;
    if(raw.read(reinterpret_cast<char*>(&n), sizeof n))
        std::cout << std::hex << std::showbase << n << '\n';
 
    // prepare file for next snippet
    std::ofstream("test.txt", std::ios::binary) << "abcd1\nabcd2\nabcd3";
 
    // read entire file into string
    if(std::ifstream is{"test.txt", std::ios::binary | std::ios::ate}) {
        auto size = is.tellg();
        std::string str(size, '\0'); // construct string to stream size
        is.seekg(0);
        if(is.read(&str[0], size)) // <- is this necessary and why?
            std::cout << str << '\n';
    }
}
DXZ
  • 451
  • 4
  • 14
  • Have you read the manual of the returned type [std::basic_ifstream](https://en.cppreference.com/w/cpp/io/basic_ifstream) and particularly its `operator bool`? – 273K Jan 05 '23 at 15:57
  • 1
    why should you check all input operations? because they are quite likely to fail. – Neil Butterworth Jan 05 '23 at 15:58
  • if the read wasn't successful then `str` doesn't contain the contents of the file as you expected it to so you shouldn't print it, maybe you should print an error instead? – Alan Birtles Jan 05 '23 at 16:02

0 Answers0