简体   繁体   中英

I'm trying to copy one text file to another using c

I'm trying to copy one test file to another in C. However my code is not working the program runs fine and produces a file CircleCode_temp but there is nothing in the text file. Any ideas why its not working

   #include <stdio.h>
   #include <stdlib.h>

   char c; 

  int main(int argc, char **argv)
  {

  FILE *orginalFile = fopen("CircleCode1", "r");
  FILE *newFile = fopen("CircleCode_temp", "w");


    if (orginalFile == NULL | newFile == NULL)
     {
       printf("Cannot open file");
       exit(0);
     }


      while((c = fgetc(orginalFile))!=EOF)
      {
         fputc(c,newFile);
         c = fgetc(orginalFile);
       }


      fclose(orginalFile);
      fclose(newFile);

     return 0;
   }
  while((c = fgetc(orginalFile))!=EOF)
  {
     fputc(c,newFile);
     c = fgetc(orginalFile);
   }

Two mistakes here:

  1. You call fgetc twice in the loop, which throws every other character away.

  2. You compare c to EOF . You're suppose to compare the return value of fgetc to EOF . If you think they're the same, remember that c is of type char and fgetc returns an int .

Also:

    if (orginalFile == NULL | newFile == NULL)

One mistake here. You have | which is bitwise OR, but you want || , which is a logical OR.

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