我正在复制一个文件的内容,然后在同一个文件上创建一个 std::ofstream,然后使用 std::copy 和一个 std::ostream_iterator 到那个 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");
}
}
最佳答案
改变这个:
std::ofstream fileOutStream("filepath.txt");
为此:
std::ofstream fileOutStream("filepath.txt", std::ios::in | std::ios::binary);
您以二进制形式打开输入文件,因此也可以对输出文件执行相同的操作。
正如 M.M 所说:
另一种选择是将两个文件都作为文本打开(在这种情况下,内存缓冲区将包含 \n
而不是 \r\n
)。
关于c++ - std::copy 正在复制一个额外的回车符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36230448/