我試圖將一個惡意文件複製到一個文本文件。所以基本上我想把mal文件的內容複製到文本文件中。 mal文件名稱爲test1.mal,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 open correct\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, newcontent);
}
printf("file created and text copied");
fclose(fp1);
fclose(fp2);
return 0;
}
那是因爲文件沒有在當前目錄中(你應該嘗試使用'GETCWD()'打印) –
'如果(FP1 == NULL || FP2 == NULL)'你確定? – Michi
使用'perror'而不是'printf'來打印錯誤信息。這會告訴你**爲什麼前面的函數調用失敗。另外,爲每個'fopen'調用分別進行錯誤檢查,以便知道哪個失敗。 – dbush