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.
the code must work for C and C++
I am compiling with multiple compilers.
I am reading and writing to the files by using the functions
fread()
and 开发者_JAVA百科fwrite()
fread()
andfwrite()
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 );
}
精彩评论