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

我使用基本的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"); 

我的问题是关于上面的代码:我打印了多行,我希望将其保存到文本文档中。 如何使用上面的代码轻松地在我的文件中包含多行代码?

将文件写入过程:

 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; } 

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

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