-2

std::ifstream::get has as one of its signatures

istream& get (char* s, streamsize n, char delim);

Should I use file.eof() as a 'delimiter' for the whole file in

 const std::string_view arg1{argv[1]}; // not a copy
 std::ifstream file (arg1.data() ,std::ios::in|std::ios::ate);

 if (file) {
   auto file_size = file.tellg(); // get file size
   std::unique_ptr<char[]> buf(new char[file_size]{} );
   file.seekg(0);         // go to beg of file

   file.get(buf.get(), file_size, file.eof());
   std::string_view sv{buf.get()};  // does not copy
}

The code works fine with no error, and no leaks, but "looks suss" to use file.eof() in this way.

273K
  • 29,503
  • 10
  • 41
  • 64
Chris Reid
  • 460
  • 4
  • 9
  • 1
    I don't think `file.eof()` necessarily fits into a `char`. – Mark Ransom Aug 26 '23 at 22:16
  • Indeed it doesn't. It must be bigger than `char`, because it has to fit all valid values for `char` and `EOF` on top of that. The valid way to read until eof is just not passing delimiter - `basic_istream& get( char_type* s, std::streamsize count );` This will read until `count` characters are read, eof happens or a failure occurs. – Yksisarvinen Aug 26 '23 at 22:21

2 Answers2

3

std::ifstream::eof() is not a data value at all. It is a boolean status flag, used to indicate whether the stream has reached its end and there is no more data available to read.

For a data delimiter, you are thinking of std::ifstream::traits_type::eof() instead, which is a data value, but not a valid one that you can use as input to std::ifstream::get(). traits_type::eof() is an output value only, used to indicate when a stream has reached its end and the read operation has no valid character to return.

For what you are attempting to do, see How do I read an entire file into a std::string in C++? (for example, this answer is similar to what you are attempting).

Remy Lebeau
  • 555,201
  • 31
  • 458
  • 770
0

Is std::ifstream::eof() a valid delimiter for std::ifstream::fget()?

No, it is not a character. It is converted to character - most probably to byte 0xff with EOF being -1.

Use file.read(buf.get(), file_size).

KamilCuk
  • 120,984
  • 8
  • 59
  • 111