Thursday, August 05, 2010

Reading image file in binary mode

#include
#include
#include
#include

int main()
{
int rc = 0;
char buffer[BUFSIZ] = {0};

FILE* p_infile = 0;
FILE* p_outfile = 0;

int length = 0;
int done = 0;

printf( "Enter the file name for the input file to be copied: " );
fgets( buffer, BUFSIZ, stdin );
buffer[ strlen( buffer ) -1 ] = 0;

p_infile = fopen( buffer, "rb" ); /* the b is added for Windoze/DOS systems... */
if( !p_infile )
{
rc = errno;
printf( "error opening %s for reading\n", buffer );
}
else
{
printf( "Enter the file name for the output file to be written: " );
fgets( buffer, BUFSIZ, stdin );
buffer[ strlen( buffer ) -1 ] = 0;

p_outfile = fopen( buffer, "wb" ); /* the b is added for Windoze/DOS systems... */
if( !p_outfile )
{
rc = errno;
printf( "error opening %s for writing\n", buffer );
}
else
{
do
{
length = fread( buffer, 1, sizeof( buffer ), p_infile );
done = length < (int)sizeof( buffer );
fwrite( buffer, 1, length, p_outfile );
}
while( !done );
}
}

if( p_infile )
{
fclose( p_infile );
p_infile = 0;
}

if( p_outfile )
{
fclose( p_outfile );
p_outfile = 0;
}
return rc;
}

參考來源:

"Here is an example that may help if all you're doing is looking to copy the file. I call this code filecopy.c, but you can call it anything that you want."
- Please Help - Reading image file in binary mode - GIDForums (在「Google 網頁註解」中檢視)

No comments: