Y
Y
yourich2013-06-26 11:27:21
linux
yourich, 2013-06-26 11:27:21

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;
}

then when running under linux, the last character in line will be 0x0D. How correctly to force to ignore reading of this character?

Thanks in advance!

Answer the question

In order to leave comments, you need to log in

3 answer(s)
E
Elsedar, 2013-06-26
@Elsedar

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.

T
turboNOMAD, 2013-06-26
@turboNOMAD

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.

Y
yourich, 2013-06-26
@yourich

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);

This code works both on windows and linux, while it is equally read as files whose lines end in both 0x0D 0x0A and 0x0A
Thank you all!

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question