-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 ?

2

2 Answers 2

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

1

Change

char c;

to

int c;

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.