【发布时间】: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++