Reading files with DOS line endings using fgets() on linux

后端 未结 4 586
小蘑菇
小蘑菇 2021-01-22 16:15

I have a file with DOS line endings that I receive at run-time, so I cannot convert the line endings to UNIX-style offline. Also, my app runs on both Windows and Linux. My app d

4条回答
  •  慢半拍i
    慢半拍i (楼主)
    2021-01-22 16:49

    You'll get what's actually in the file, including the \r characters. In unix there aren't text files and binary files, there are just files, and stdio doesn't do conversions. After reading a line into a buffer with fgets, you can do:

    char *p = strrchr(buffer, '\r');
    if(p && p[1]=='\n' && p[2]=='\0') {
        p[0] = '\n';
        p[1] = '\0';
    }
    

    That will change a terminating \r\n\0 into \n\0. Or you could just do p[0]='\0' if you don't want to keep the \n.

    Note the use of strrchr, not strchr. There's nothing that prevents multiple \rs from being present in the middle of a line, and you probably don't want to truncate the line at the first one.

    Answer to the EDIT section of the question: yes, the "b" in "rb" is a no-op in unix.

提交回复
热议问题