0

Apparently, on Linux (Centos 7, g++ (GCC) 4.8.5 20150623 (Red Hat 4.8.5-4)) you can seek to absurd offsets in files opened for reading. I can get the file length and check the offset myself, but shouldn't the seekg fail?

This program illustrates. No error conditions are detected, but the file is much less than 999999 bytes long.

#include <iostream>
#include <fstream>

int main(int argc, char **argv) {

    std::ifstream f("./tstseek.cpp",std::ios::in);
    if(!f.seekg(9999999)) {
        std::cerr << "SEEK FAILED" << std::endl;
    }
    long int pos = f.tellg();
    if(f.bad() || f.fail()) {
        std::cerr << "SEEK FAILED" << std::endl;
    }
    if(f.eof()) {
        std::cerr << "EOF AFTER SEEK" << std::endl;
    }
    std::string s;
    std::getline(f,s);
    if(f.bad() || f.fail()) {
        std::cerr << "getline failed" << std::endl;
    }
    if(f.eof()) {
        std::cerr << "EOF after getline" << std::endl;
    }
    std::streamsize bytesread = f.gcount();
    std::cerr << "Position after seekg(9999999) = " << pos << std::endl
                 << "bytes read = " << bytesread << std::endl
                 << "string=[" << s << "]" << std::endl;
}
  • I would think you would want to check the fail bit immediately after the call to seekg, not just after an intervening call to tellg. – Dan Korn Oct 05 '16 at 22:40
  • Not the problem, but don't use `std::endl` unless you need the extra stuff that it does. `'\n'` ends a line. Especially when you're writing to `std::cerr`, which is line-buffered, i.e., it flushes the stream after each line, so the flush that `std::endl` does is pointless. – Pete Becker Oct 06 '16 at 01:50
  • @PeteBecker, I've been using std::endl for over a decade, and if it does too much or does things that don't need doing, I've never noticed. I've done extensive profiling for performance on CPU bound programs, and std::endl vs '\n' has never been the problem. – kent williams Nov 17 '16 at 22:37
  • @DanKorn: the seek always seems to succeed, which makes sense for files you want to write. It's conceivable to want to write at arbitrary locations in a file. But when the file is opened for reading it doesn't make much sense to be able to seek past end of file. To me anyway. – kent williams Nov 17 '16 at 22:38
  • @kentwilliams - it's not at all surprising that excessive (and usually redundant) output flushes don't affect performance of cpu-bound programs. Similarly, horribly inefficient algorithms won't affect the performance of I/O bound programs. That doesn't make them a good thing. Do you think beginners should taught to use `std::endl` rather than `'\n'`? If so, why? – Pete Becker Nov 17 '16 at 22:40

0 Answers0