tags:

views:

119

answers:

2

Hi, 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, c++

2) i am compiling with multiple compilers.

3) I am reading and writing to the files by using the functions fread() and 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?

Thanks.

+9  A: 

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

PeterK
I am doing read/write in binary. fread and fwrite work in binary.
aCuria
@aCuria Are you fopen("file.txt","rb")/fopen("file.txt","wb")?
Artyom
@aCuria You need to open the file in binary mode.
anon
Just to clarify, did you open the file in binary mode? pFile = fopen ( "myfile.txt" , "wb+" );
semaj
Thanks Artyom, Neil This is exactly the problem. +1
aCuria
+2  A: 
#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 );
}
anon