Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove Carriage Returns from char* (C++)

Tags:

c++

I have defined a resource file in my Visual Studio 2008 C++ project. The problem is that after obtaining the resource data with LockResource method the resulting char buffer contains Carriage Returns and Line Feeds where as the original data contained only Line feeds. For instance if the original line contains:

00 0A FC 80 00 00 27 10 00 0A FC 80 00 00 27 10

The resulting char* contains also Carriage Returns (0D):

00 0D 0A FC 80 00 00 27 10 00 0D 0A FC 80 00 00

I tried the following code to get rid of them but this results in both carriage return and line feed to be removed:

for (int i = 0; i < sz; ++i)
{
    // Ignore carriage returns
    if (data[i] == '\n') continue;
    // ...
}

How do I get rid of Carriage Returns but leave New Line characters?

EDIT:

To make it more specific. I am writing the char buffer into the file:

std::ofstream outputFile(fileName.c_str());

for (int i = 0; i < sz; ++i)
{
    // Ignore carriage returns
    // if (data[i] == '\r') continue; This leaves both CR and LF 
    // if (data[i] == 0x0D) continue; This leaves both CR and LF
    if (data[i]) == '\n') continue; //This removes both CR and LF
    outputFile << data[i];
}
like image 304
BadCoder Avatar asked Dec 07 '22 21:12

BadCoder


1 Answers

When you write a '\n' to a text file it is converted into the 'End of Line Sequence'. In your case this looks like '\r\n'. When you read from a text file the 'End of Line Sequence' is converted back into a single '\n' character. So for normal processing this extra character should not affect you (assuming you open both read/write as text files).

If you do not want your '\n' converted into the 'End of Line Sequence' then open the file as binary. When this is done then no processing is done on the '\n' character.

std::ofstream outputFile(fileName.c_str(), std::ios::binary);
                                        // ^^^^^^^^^^^^^^^^

But note: The file representation should not affect you. If you open and read the file as text the '\r\n' will be converted back into a single '\n' character within your application.

like image 99
Martin York Avatar answered Dec 25 '22 03:12

Martin York