我想编写一个小函数,它将文件作为输入,并通过以下更改写入输出文件:
\r\n) 作为 EndOfLine ,则应仅用 LF ( \n) 替换。\n),则应将其替换为 CRLF ( \r\n)有关这方面的更多信息,请参阅这篇文章。
这是我这样做的尝试:
bool convertFile(string location) {
ifstream input;
ofstream output;
input.open(location);
if(!input.is_open()){
cout << "Invalid location!" << endl;
return false;
}
int dot = location.find_last_of('.');
if(dot != string::npos) location.replace(dot, 1, "_new.");
output.open(location);
char c;
for(;;){
input.get(c);
if(!input.good()){
if(input.eof()) return true;
else return false;
}
if(c == '\r'){
input.get(c);
if(c == '\n') output << '\n'; // \r\n -> \n
else output << '\r' << c; // leave as it was, I dont know if this is needed
} else if (c == '\n'){
output << "\r\n"; // \n -> \r\n
} else {
output << c;
}
}
Run Code Online (Sandbox Code Playgroud)
但是,这并没有按预期工作。
通过此输入:
我得到这个输出:
我尝试通过调试我的脚本来解决这个问题,我发现它if(c == '\r')永远不会计算为 true,所以看起来\r我的 中没有 ' .txt,而 Notepad++ 说我有。
我使用的是Windows,这是我能想到的唯一可能导致这种情况的事情,但我不知道如何造成的。
当您以文本模式打开文件时,输入流已经转换行结尾。如果您想完全控制,请以二进制模式打开文件。
input.open(location, std::ios::binary);
output.open(location, std::ios::binary);
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
361 次 |
| 最近记录: |