Christina F.
Christina F.

Reputation: 21

Why is my fread fwrite program not copying the first character over in C?

Help with using Malloc / freads /fwrites?? The first letter isn't copying over?

   while((c = getc(in))!=EOF){
      fread(point, length, 1, in);  
      fwrite(point, length, 1, final); 
   }

Upvotes: 1

Views: 303

Answers (2)

Chan Kha Vu
Chan Kha Vu

Reputation: 10400

Assuming that your input from file and output to file works correctly, here is some problem with the code chunk you provided:

  • You declared ptr as (int*)malloc(count). The problem is, ptr here is treated as an array of integers, which means each element has the size of 4 bytes instead of 1, so count must be a multiple of 4. If you want to use ptr to store char symbols, change it to ptr = (char*)malloc(count), or ptr = (int*) malloc(sizeof(int) * count) if your 'symbols' are actually 4 byte integers;

  • You read characters to the variable c, but you're not using it.

  • According to this description, the second parameter of fread and fwrite are the size of your elements, and the third is the number of elements you want to read/write.

  • If you want to do fread until end of file, there's no need to do while ((c=getc(in)) != EOF)..., just follow this stackoverflow post

Hope this helps.

Upvotes: 1

getc reads a character into c. So the first character will be stored into c, and the next one will be the second character.

Then fread reads a bunch of characters (count of them) into the memory pointed to by ptr. So the second, third, ..., count+1'th characters will be stored into that memory.

Then fwrite writes them (of course).

(Then your program repeats this until it gets to the end of the file)

Upvotes: 3

Related Questions