Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

std::copy is copying an extra carriage return character

Tags:

c++

I'm copying the contents of a file, then creating a std::ofstream upon the same file, and then using std::copy with a std::ostream_iterator to that std::ofstream to copy the copied contents back into the file.

My issue is that a new, blank line is getting inserted between each original line.

Here is my code:

std::string firstFile = getFileContents_asString("filepath.txt");
std::ofstream fileOutStream("filepath.txt");
std::ostream_iterator<char> oi(fileOutStream);
std::copy(firstFile.begin(), firstFile.end(), oi);

It takes text like this:

#include "worklogger_pres_model.h"
#include "worklogmodel_container.h"
#include <QSqlRelationalTableModel>

And does this:

#include "worklogger_pres_model.h"

#include "worklogmodel_container.h"

#include <QSqlRelationalTableModel>

In checking out things with a debugger, upon a first debug run, the firstFile string has stretches like this model.h\r\n#includ.

Upon a second debug run, the firstFile string has stretches like this model.h\r\r\n#includ.

Why is std::copy copying an extra \r or carriage return, per each carriage return occurrence, back into the file?

If it turns out to be helpful, here is the getFileContents_asString method.

std::string getFileContents_asString(const char * filename) {
    std::ifstream f (filename, std::ios::in | std::ios::binary);
    if (f) {
        std::string buffer;
        f.seekg(0, std::ios::end);
        buffer.resize(f.tellg());
        f.seekg(0, std::ios::beg);
        f.read(&buffer[0], buffer.size());
        f.close();
        return buffer;
    } else {
        std::cout << "file could not be opened";
        return std::string("failure to open file");
    }
}
like image 750
RedKrovvy Avatar asked Nov 26 '25 04:11

RedKrovvy


1 Answers

Change this:

std::ofstream fileOutStream("filepath.txt");

to this:

std::ofstream fileOutStream("filepath.txt", std::ios::in | std::ios::binary);

You open the input file in binary, so it would make sense to do the same for the output file too.


As M.M said:

Another option is to open both files as text (in which case the memory buffer will contain \n instead of \r\n).

like image 175
gsamaras Avatar answered Nov 27 '25 19:11

gsamaras



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!