2011-11-30 93 views
1

我在寫一個基本程序,它從現有文本文件複製一個字符串並將文本複製到一個新的文本文件中。我快到了,但我遇到了一些小問題。首先,我在複製後將文本行輸出到屏幕上,並在字符串後給出3個隨機字符。我想知道爲什麼會發生這種情況。此外,該程序正在創建新的文本文件,但不會將字符串放入文件中。將數據從一個文本文件複製到另一個文本文件C

這裏是我的代碼:

#include <stdio.h> 
#include <string.h> 
#include <stdlib.h> 

int main(void) 
{ 
char content[80]; 
char newcontent[80]; 

//Step 1: Open text files and check that they open// 
FILE *fp1, *fp2; 
fp1 = fopen("details.txt","r"); 
fp2 = fopen("copydetails.txt","w"); 

    if(fp1 == NULL || fp2 == NULL) 
    { 
    printf("Error reading file\n"); 
    exit(0); 
    } 
    printf("Files open correctly\n"); 
//Step 2: Get text from original file// 
while(fgets(content, strlen(content), fp1) !=NULL) 
    { 
    fputs (content, stdout); 
    strcpy (content, newcontent); 
    } 
    printf("%s", newcontent); 
printf("Text retrieved from original file\n"); 

//Step 3: Copy text to new file// 
    while(fgets(content, strlen(content), fp1) !=NULL) 
     { 
      fprintf(fp2, newcontent); 
     } 
     printf("file created and text copied to it"); 
//Step 4: Close both files and end program// 
     fclose(fp1); 
     fclose(fp2); 
return 0; 
} 

回答

1

你需要改變:

while(fgets(content, strlen(content), fp1) !=NULL) 

您需要的sizeof陣列content,而不是長度。

while(fgets(content, sizeof(content), fp1) !=NULL) 

就算你使用它strlen()將返回0之前初始化content,你會從文件中讀取什麼。

另外,如果要在寫入新文件時重新讀取輸入文件,則需要輸入fclose()或輸入文件fopen()rewind()

+0

我已經將strlen改爲sizeof,但它仍然沒有寫入新文件。任何其他想法? – adohertyd

+0

你是否改變了兩個'fgets()'使用'sizeof'並確保你再次處於輸入文件的開頭? – hmjd

+0

你我的朋友是一個拯救生命的人。您介意解釋爲什麼我必須關閉並重新打開輸入文件嗎?另外,是否有一種「更清潔」的方式來執行這個程序?我是C編程的新手,並試圖改進。再次感謝 – adohertyd

1

在的strcpy秒和dest的順序顛倒

也非常我不會複製,而是Concat的緩衝區。

+0

我已經做了相反的事情,並已消除了奇怪的字符,但它現在輸出原始文本文件的內容兩次。 – adohertyd

+0

理想情況下,您應該打開兩個從緩衝區中讀取的文件。將緩衝區寫入第二個文件,直到全部被讀取。然後關閉這兩個文件。 –

+0

那是什麼代碼?我對使用緩衝區不是很熟悉。我們的講師只是簡單地談到了這一點。 – adohertyd

1

程序的這一修改後的版本將做的工作:

#include <stdio.h> 
#include <string.h> 
#include <stdlib.h> 

int main(void) 
{ 
    char content[80]; 

    //Step 1: Open text files and check that they open// 
    FILE *fp1, *fp2; 
    fp1 = fopen("details.txt","r"); 
    fp2 = fopen("copydetails.txt","w"); 

    if(fp1 == NULL || fp2 == NULL) 
    { 
     printf("\nError reading file\n"); 
     exit(0); 
    } 
    printf("\nFiles open correctly\n"); 

    //Step 2: Get text from original file// 
    while(fgets(content, sizeof(content), fp1) !=NULL) 
    { 
     fprintf(fp2, "%s", content); 
    } 

    printf("File created and text copied to it\n\n"); 

    //Step 4: Close both files and end program// 
    fclose(fp1); 
    fclose(fp2); 
    return 0; 
} 
-3

您在本使用: _ fprintf中(FP2,newcontent); _

和 「fprintf中」 簽名 int fprintf(FILE * stream,const char * format,...); 你錯過了

相關問題