2017-04-06 38 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