-1

I am trying to solve a problem which requires me to read a file and generate another file which has the same contents as the original but every fourth byte removed.I tried it doing this way ...

int main()
{
  FILE *p;
  FILE *q;
  int i=0,k=0;
  char c;

  p = fopen("C:\\Users\\Teja\\Desktop\\Beethoven.raw","rw");
  q = fopen("C:\\Users\\Teja\\Desktop\\Beethoven_new.raw","w+");

  printf("%x is the EOF character \n",EOF);
  while((c=fgetc(p))!=EOF)
  {

     if(i==3){
      i=0;
      printf("Removing %x %d \n",c,k++);
     }
     else{
      printf("Putting %x %d \n",c,k++);
      fputc(c,q);
      i++;
     }
  }
  fclose(p);
  fclose(q);

  return 0;
}

The file that i was trying to read is a .raw file and it is around 10-15 MB. I notice that the above code stops reading the file after typically 88 bytes. Is there any way to read large files or am i doing anything wrong ?

Flash
  • 2,901
  • 5
  • 38
  • 55

2 Answers2

2

In addition to what has already been pointed out, a note on opening files: It sounds like your file in a binary file, which means you must add a b to the mode string. Additionally, rw is not a mode, since you only read from p you want rb, and since you only write to q you want wb or wb+.

By the way, the reason why you need fgetc to return an int is because fgetc must return 257 unique values: all the possible values of char, that is 0x00 thru 0xFF as well as something unique to signify EOF, usually -1

Dan
  • 10,531
  • 2
  • 36
  • 55
1

Change

char c;

to

int c;

as the return type of fetgetc() is an int and not char.

codaddict
  • 445,704
  • 82
  • 492
  • 529