mercredi 2 janvier 2019

stringstream of a file returns newline at the end even if there is no new line added in the actual file

Scenario:
I use the following logic to read the content of a file using C++ on a unix and linux environment.

#include <fstream>
#include <sstream>

std::ifstream file("/some/file");
std::stringstream sstr;
sstr << file.rdbuf();
std::string str = file.str();

Lets say the file contains following text.

abcdefgh

Above file content was created on MacOS HighSierra using vim as editor.

I tested the code on my OSX machine and found the the content of str contains a \n in the end along the file content. So the variable str contains abcdefgh\n. This happens in spite of the fact that I have not entered a new line on the file which contains abcdefgh.

This looks a bit un-natural to me since if I want to compare the content a file with a matching string to check something then I will have explicitly remove \n before the comparison.

Question:
Firstly, am I doing something wrong with the way I am reading the file?

Secondly, is it expected for me to removed the \n to get the exact content of the file?

Aucun commentaire:

Enregistrer un commentaire