Alright so this is a bizarre cross platform thing that I’m experiencing with text files. Say I have a program that very simply reads a text file
// reading a text file
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main () {
string line;
ifstream myfile ("example.txt");
if (myfile.is_open())
{
while ( myfile.good() )
{
getline (myfile,line);
if (line == "BEGIN")
cout << line << endl;
}
myfile.close();
}
else cout << "Unable to open file";
return 0;
}
So this reads a text file and spits out the line it is reading if it encounters BEGIN. Here is the text file I am reading:
HEADER
BEGIN
X 2
Y 2
Z 1
END
Windows successfully spits out BEGIN one time, since it is encountered one time. Linux spits nothing out. Is there something fundamental that I’m missing here?
If the file has windows line-endings (that is, every line ends with carriage-return + line-feed, rather than just line-feed as Linux expects), then
linewill be"BEGIN\r"rather than"BEGIN"on Linux.To fix this, you can run
dos2unixon the file to convert it to Linux line-endings:Alternatively, if you want the file to be identical on both systems, you can open it in binary mode rather than text mode:
and then both systems will read the file the same way. (If it uses Windows line-endings, then your program will have to handle the carriage returns, but at least you’ll see consistent behavior.)