2009-09-09 86 views
0

我使用的是基本的C代碼打印到一個文本文件:將多行添加到文本文件輸出?

FILE *file; 
file = fopen("zach.txt", "a+"); //add text to file if exists, create file if file does not exist 

fprintf(file, "%s", "This is just an example :)\n"); //writes to file 
fclose(file); //close file after writing 

printf("File has been written. Please review. \n"); 

我的問題是關於上面的代碼:我有多條線路我已經印刷,我想保存到文本文件。如何使用上面的代碼輕鬆地將多行代碼打印在我的文件中?

+0

我想我的主要問題是我可以包裹我的多行函數或東西或varilable,只需調用該變量打印出多行代碼? – HollerTrain 2009-09-09 23:34:53

+0

家庭作業感...刺痛 – 2009-09-09 23:41:51

+0

@約翰,哈哈是的,它是作業:)但我想學習這個,而不是找到簡單的答案,然後逃跑:)我感謝任何人的幫助;) – HollerTrain 2009-09-10 00:10:48

回答

2

移動文件寫入到一個程序:

void write_lines (FILE *fp) { 
    fprintf (file, "%s\n", "Line 1"); 
    fprintf (file, "%s %d\n", "Line", 2); 
    fprintf (file, "Multiple\nlines\n%s", "in one call\n"); 
} 

int main() { 
    FILE *file = fopen ("zach.txt", "a+"); 
    assert (file != NULL); // Basic error checking 
    write_lines (file); 
    fclose (file); 
    printf ("File has been written. Please review. \n"); 
    return 0; 
} 
+0

爲什麼不使用'fputs()'並避免格式字符串的危險和開銷?無論如何,這就是你實際上正在做的事情。 – 2009-09-09 23:46:13

+0

您也可以避免必須反覆調用fprintf或fputs。 #define my_string「line1 \ nline2 \ nline3」 fputs(my_string,file); – KFro 2009-09-09 23:49:56

+0

@KFro - 注意''fputs()'不會像普通'puts()'(標準錯誤mutch?)那樣追加換行符。不過,我更喜歡把它分成多個不同的函數調用,或者使用字符串文字的自動連接來將字符串的行放在它們自己的行上。不需要用宏來隱藏它。 – 2009-09-09 23:52:25

1

有很多方法可以做到這一點,這裏有一個:

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

int appendToFile(char *text, char *fileName) { 

    FILE *file; 

    //no need to continue if the file can't be opened. 
    if(! (file = fopen(fileName, "a+"))) return 0; 

    fprintf(file, "%s", text); 
    fclose(file); 

    //returning 1 rather than 0 makes the if statement in 
    //main make more sense. 
    return 1; 

} 

int main() { 

    char someText[256]; 

    //could use snprintf for formatted output, but we don't 
    //really need that here. Note that strncpy is used first 
    //and strncat used for the rest of the lines. This part 
    //could just be one big string constant or it could be 
    //abstracted to yet another function if you wanted. 
    strncpy(someText, "Here is some text!\n", 256); 
    strncat(someText, "It is on multiple lines.\n", 256); 
    strncat(someText, "Hooray!\n", 256); 

    if(appendToFile(someText, "zach.txt")) { 
     printf("Text file ./zach.txt has been written to."); 
    } else { 
     printf("Could not write to ./zach.txt."); 
    } 

    return 0; 

} 

通知strncpystrncat功能,因爲你是不是真的利用xprintf函數附帶的格式化輸入。