【问题标题】:Copying files in C program, but file is blank在C程序中复制文件,但文件为空白
【发布时间】:2017-09-02 04:23:45
【问题描述】:

我正在尝试将文件 test1.mal 的内容复制到 output.txt 中,并且程序说它正在这样做并且所有内容都可以编译,但是当我打开 output.txt 文件时,它是空白的...谁能告诉我哪里出错了?

#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;
}

【问题讨论】:

  • strcpy (content, newcontent); 的意义何在?调试? newcontent 未初始化!也许你想要strcpy (newcontent, content);
  • 那么程序写入 output.txt 的部分在哪里?如果程序不写任何东西,那么什么都不会写。

标签: c file-io file-copying


【解决方案1】:

您正在将文件复制到标准输出:

fputs(content, stdout);

必须替换为

fputs(content, fp2);

或者,当您使用 fprintf 写入输出文件时,文件的光标已经在末尾。您可以使用 fseek() 和 SEEK_SET 来将其置于开头。

【讨论】:

    【解决方案2】:

    您只需要一个缓冲区即可从输入文件中读取并将其写入输出文件。而且您需要在最后关闭文件以确保数据被刷新。

    #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;
    }
    

    【讨论】:

    • 谢谢!但文件仍然是空的。它正在创建一个新文件,但就是这样
    • 你在当前目录下名为test1.mal的文件有什么吗?
    • 是的! test1.mal和output.txt和c程序都在一个文件夹里。
    【解决方案3】:

    首先,你应该记住,在意识形态上更真实的是在这里使用“rb”、“wb”。当输入存在时,您必须将字节从一个文件复制到另一个文件。

    #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】:

      您将文件读到最后,写入标准输出。当您尝试进入第二个循环再次读取它时……您什么也得不到,因为您已经读取了整个文件。尝试rewindfseek 回到开头。或者只是重新打开文件。换句话说,只需添加:

      rewind(fp1);
      

      在第二个 while 循环之前。

      【讨论】:

      • 我尝试在第二个 while 循环之前添加它,但仍然没有运气:/
      猜你喜欢
      • 1970-01-01
      • 2017-09-02
      • 2020-04-13
      • 1970-01-01
      • 2014-04-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-06-28
      相关资源
      最近更新 更多