Ifstream :: read doesnot append '\ 0'

ifstream::read just reads n bytes into the buffer, but doesn't add '\0' to the end of the buffer, right? Then, when I use the buffer, how does it know the end of the buffer?

Should I manually add '\0' to the end of the buffer?

+4
source share
5 answers

ifstream used to read from a file, binary or text. When you work with a binary file with read , you cannot be sure of the origin of the null byte (from the file itself or when adding read ), so reading does not add a null destination buffer.

If you are working on a text file, you can use std :: getline and get std::string :

 istream& getline ( istream& is, string& str ); 
+3
source

Yes, you're right, you need to manually add it to the end of the buffer: buffer[length] = '\0'; if you need a null terminator. When you call write , you can also specify the length of the output: std::cout.write(buffer, length); which will only output length amount of data to tell you when to stop requiring you to use a null terminator. I would look at std::getline and std::string for a more robust approach.

+1
source

If you read in std::string , say, with std::getline , then the string carries a length - std::string does not end with '\0' like a C-style char* string. If you read in std :: string and then use string.c_str (), this will be null-terminated. You can use this for a C style string.

If you read in char* , you must specify the length - the number of bytes to read, regardless of any '\0' . In this case, you must manually add "\ 0" at the end of the buffer.

+1
source

You can put whatever you want at the end of the buffer as long as there is room for it. istream::read does not tell you how many bytes it reads; it either reads everything you requested, or changes the state of the stream to fail / eof.

If you want to handle a case where you may have fewer bytes than expected, use istream::readsome , it returns the number of bytes retrieved.

As the other answers mentioned, if you are dealing with strings, use functions that read strings, such as std::getline or extractors >> . istream::read for binary data - in this case std::streambuf usually more convenient to use.

0
source

You can call ifstream::gcount() to determine the number of characters read in the read() operation.

0
source

All Articles