Copying files in C program, but file is blank

拥有回忆 提交于 2019-12-11 04:52:10

问题


I'm trying to copy the content of the file test1.mal into an output.txt and the program says it is doing so and everything compiles, but when I open the output.txt file, it is blank...Could someone tell me where I am going wrong?

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


int main(void) {

char content[255];
char newcontent[255];

FILE *fp1, *fp2;
fp1 = fopen("test1.mal", "r");
fp2 = fopen("output.txt", "w");

if(fp1 == NULL || fp2 == NULL)
{
printf("error reading file\n");
exit(0);
}
printf("files opened correctly\n");
while(fgets(content, sizeof (content), fp1) !=NULL)
{
fputs(content, stdout);
strcpy (content, newcontent);
}

printf("%s", newcontent);
printf("text received\n");

while(fgets(content, sizeof(content), fp1) !=NULL)
{
fprintf(fp2, "output.txt");
}
printf("file created and text copied\n");

//fclose(fp1);
//fclose(fp2);
//return 0;
}

回答1:


You are copying the file to the standard outpout :

fputs(content, stdout);

Have to be replaced by

fputs(content, fp2);

Either, when you use fprintf to write in your output file, the cursor of the file is already at the end. You can use fseek() with SEEK_SET to place it a the beginning.




回答2:


You only need one buffer to read from the input file and write it to the output file. And you need to close the file at the end to make sure that data gets flushed.

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

int main(int argc, char** argv) {
  char content[255];
  FILE *fp1, *fp2;
  fp1 = fopen("test1.mal", "r");
  fp2 = fopen("output.txt", "w");

  if(fp1 == NULL || fp2 == NULL){
   printf("error reading file\n");
   exit(0);
  }
  printf("files opened correctly\n");

  // read from input file and write to the output file
  while(fgets(content, sizeof (content), fp1) !=NULL) {
    fputs(content, fp2);
  }

  fclose(fp1);
  fclose(fp2);
  printf("file created and text copied\n");
  return 0;
}



回答3:


First of all , you should keep in mind that ideologically more true is to use "rb", "wb" here. You must just copy bytes from one file to another while input exists.

#include <stdio.h>

int main() {
    freopen("input.txt", "rb", stdin);
    freopen("output.txt", "wb", stdout);
    unsigned char byte;
    while (scanf("%c", &byte) > 0)
        printf("%c", byte);

    return 0;
}



回答4:


You read the file through to the end, writing to stdout. When you try to enter the second loop to read it again...you get nothing because you've already read the whole file. Try rewind or fseek to go back to the beginning. Or just reopen the file. In other words, just add:

rewind(fp1);

before the second while loop.



来源:https://stackoverflow.com/questions/43267023/copying-files-in-c-program-but-file-is-blank

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!