【问题标题】:std::copy is copying an extra carriage return characterstd::copy 正在复制一个额外的回车符
【发布时间】:2016-07-13 19:54:53
【问题描述】:

我正在复制一个文件的内容,然后在同一个文件上创建一个 std::ofstream,然后使用带有 std::ostream_iterator 的 std::copy 到该 std::ofstream 将复制的内容复制回来进入文件。

我的问题是在每个原始行之间插入了一个新的空白行。

这是我的代码:

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

它需要这样的文本:

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

然后这样做:

#include "worklogger_pres_model.h"

#include "worklogmodel_container.h"

#include <QSqlRelationalTableModel>

在使用调试器检查时,在第一次调试运行时,firstFile 字符串的长度类似于 model.h\r\n#includ

在第二次调试运行时,firstFile 字符串的长度类似于 model.h\r\r\n#includ

为什么 std::copy 会在每次出现回车时将额外的 \r 或回车复制回文件中?

如果有帮助,这里是 getFileContents_asString 方法。

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

【问题讨论】:

  • 也以“二进制”模式打开输出文件。

标签: c++


【解决方案1】:

改变这个:

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

到这里:

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

您以二进制格式打开输入文件,因此也可以对输出文件执行相同操作。


正如MM所说:

另一种选择是以文本形式打开这两个文件(在这种情况下,内存缓冲区将包含\n 而不是\r\n)。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-03-12
    • 1970-01-01
    • 2015-01-05
    • 1970-01-01
    • 2011-04-30
    相关资源
    最近更新 更多