1 / 5
Jan 2011

Their common syntax is:
[bbone=cpp,94]
size_t fwrite ( const void * ptr, size_t size, size_t count, FILE * stream );
size_t fread ( const void * ptr, size_t size, size_t count, FILE * stream );

[/bbone]

I understand fread reads total size * count bytes from the stream. Now, the problem is, does it matter if I switch the parameters size and count? The strange thing is, when I use something like this:
[bbone=cpp,95]#include

const int BUFF = 1000000;
char buff[BUFF];

int main() {
freopen("in.txt", "r", stdin);
freopen("out.txt", "w", stdout);
int n = (int)fread(buff, 1, BUFF, stdin);
fwrite(buff, 1, n, stdout);
return 0;
}
[/bbone]

This works just fine, but if I switch 1 and BUFF, that is, fread(buff, BUFF, 1, stdin), it always returns 0, but it reads the stream successfully and sometimes it has repeating part in the end, not always. That's why I am quite confused about the behavior of these functions.

They provide a fast way to read/write IO files. Now, do their performance depend on how I pass the size and count?, to read 10000 bytes of data, I think this is better fread(ptr, 10000, 1, fp); but if I call like this, it causes problems.

Thanks in advance.

n = The total number of elements successfully read

 int n = (int)fread(buff, 1, BUFF, stdin);

size of element = 1
n = number of characters in the input file or BUFF ( depending on which is smaller ).

 int n = (int)fread(buff, BUFF, 1, stdin);

size of element = BUFF
n = 0, if no of characters in input file < BUFF
n = 1, if no of characters in input file >= BUFF

If you use the first implementation and there aren't 10000 bytes fread will return how many bytes that were read. (how many successful calls to fgetc were made). Your second method will return 0.

9 days later
1 month later

I have been trying to write a simple C program to use fread and fwrite to read some data from a file and write it into another file. It works, though i always seem to get some extra text at the end. Usually part of the original text. Heres my code. Any help is much appreciated.

thanks,


include

int main( void)
{
unsigned char *buff;
FILE *fptr;
FILE *fptr2;

if (( fptr = fopen("file.txt", "rb" )) == NULL || (fptr2 = fopen("file2.txt", "wb")) == NULL){
printf( "File could not be opened.\n");
}

else {
while ( !feof(fptr)){

fread (buff , 1 , sizeof(buff) , fptr );
fwrite (buff , 1 , sizeof(buff) , fptr2 );

}
fclose(fptr);
fclose(fptr2);
}
}