Answer the question
In order to leave comments, you need to log in
How to remove carriage return character (0x0D) when reading files in linux in C++
Hello!
There is a file generated in windows, respectively, the end of the line in it is indicated by two consecutive characters 0x0D 0x0A.
Need to read lines from this file in linux. If you organize reading like this:
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main()
{
ifstream file("file.txt");
string line;
std::getline(file, line);
return 0;
}
Answer the question
In order to leave comments, you need to log in
I would probably not bother and just check for the presence of \r at the end of the line, and if it is present, then I would delete it via .erase().
Or better yet, just convert the entire file.
Look at this overloaded version of getline:
basic_istream& getline (char_type* s, streamsize n, char_type delim);
If you specify 0x0D as the delim parameter, then this character will not be in the read lines.
In general, the following was done:
std::getline(file, line);
size_t len = line.length();
if (len && (line.c_str()[len - 1] == 0x0D) ) // linux read
line.erase(len - 1);
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question