开发者

File IO, Handling CRLF

I am writing a program that takes a file and splits it up into multiple small files of a user specified size, then join the multiple small files back again.

  1. the code must work for C and C++

  2. I am compiling with multiple compilers.

  3. I am reading and writing to the files by using the functions fread() and 开发者_JAVA百科fwrite()

  4. fread() and fwrite() handle bytes, not strings.

The problem I am having pertains to CRLF. If the file I am reading from contains CRLF, then I want to retain it when i split and join the files back together. If the file contains LF, then i want to retain LF.

Unfortunately, fread() seems to store CRLF as \n (I think), and whatever is written by fwrite() is compiler-dependent.

How do I approach this problem?


Do the read/write in binary mode. That should make it irrelevant whether there are CRLF or LF line endings.


#include <stdio.h>

int main() {
    FILE * f = fopen( "file.txt", "rb" );
    char c;
    while( fread( &c, 1, 1, f ) ) {
        if ( c == '\r' ) {
            printf( "CR\n" );
        }
        else if ( c == '\n' ) {
            printf( "LF\n" );
        }
        else {
            printf( "%c\n" , c );
        }
    }
    fclose( f );
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜