将 .txt 文件从 CRLF 转换为 LF 并返回

Mar*_*ler 0 c++ newline txt

我想编写一个小函数,它将文件作为输入,并通过以下更改写入输出文件:

  • 如果输入文件使用 CRLF ( \r\n) 作为 EndOfLine ,则应仅用 LF ( \n) 替换。
  • 如果使用 LF ( \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,这是我能想到的唯一可能导致这种情况的事情,但我不知道如何造成的。

Tho*_*ler 5

当您以文本模式打开文件时,输入流已经转换行结尾。如果您想完全控制,请以二进制模式打开文件。

input.open(location, std::ios::binary);
output.open(location, std::ios::binary);
Run Code Online (Sandbox Code Playgroud)

  • @MarcMiller:在文本模式下,读取时`\r\n`将转换为`\n`。写入时,`\n`会被转换为`\r\n`。 (2认同)