小编Mar*_*ler的帖子

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

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

  • 如果输入文件使用 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 …
Run Code Online (Sandbox Code Playgroud)

c++ newline txt

0
推荐指数
1
解决办法
361
查看次数

标签 统计

c++ ×1

newline ×1

txt ×1