简体   繁体   中英

Having problems Reading a file in C

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 ?

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

Change

char c;

to

int c;

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM