将多行添加到文本文件输出?

问题描述:

我使用的是基本的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

移动文件写入到一个程序:

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

有很多方法可以做到这一点,这里有一个:

#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函数附带的格式化输入。