1

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); 
   }

2 Answers2

3

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)

user253751
  • 57,427
  • 7
  • 48
  • 90
1

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.

Community
  • 1
  • 1
Chan Kha Vu
  • 9,834
  • 6
  • 32
  • 64