2017-04-06 39 views
1

我试图将文件test1.mal的内容复制到output.txt中,程序说它正在这样做并且编译了所有内容,但是当我打开output.txt文件时,它是空白...有人能告诉我我要去哪里吗?在C程序中复制文件,但文件为空

#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

'strcpy(content,newcontent);'?调试? 'newcontent'没有初始化!也许你想'strcpy(newcontent,content);' – chux

+0

那么程序写入output.txt的地方在哪里呢?如果程序没有写入任何内容,则不会写入任何内容。 – immibis

回答

0

您将文件复制到标准outpout:

fputs(content, stdout); 

必须由

fputs(content, fp2); 

要么被替换,当您使用fprintf中在输出文件中写入时,文件的光标已经在最后。您可以使用fseek()和SEEK_SET将它放在开头。

0

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

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

谢谢!但该文件仍然是空的。它正在创建一个新文件,但多数民众赞成 – chris2656

+0

你有什么在当前目录中名为'test1.mal'的文件? – Arash

+0

是的! test1.mal和output.txt和c程序都在一个文件夹中。 – chris2656

0

首先,您应该记住,思想上更真实的是在这里使用“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; 
} 
0

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

rewind(fp1); 

第二while循环之前。

+0

我试图在第二个while循环之前添加,仍然没有运气:/ – chris2656