在C程序中复制文件,但是文件是空白的 [英] Copying files in C program, but file is blank

查看:233
本文介绍了在C程序中复制文件,但是文件是空白的的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图将文件 test1.mal 的内容复制到 output.txt 中,程序说,它是这样做,一切都编译,但是当我打开 output.txt 文件,它是空白的...有人可以告诉我,我要去哪里错了吗? / p>

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


推荐答案

最后,写入标准输出。当你尝试进入第二个循环再次阅读...你什么也没有得到,因为你已经阅读了整个文件。试试倒带 fseek 回到开头。或者只是重新打开文件。换句话说,只需添加:

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);

在第二个循环之前。

这篇关于在C程序中复制文件,但是文件是空白的的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆