原文: https://www.programiz.com/c-programming/examples/write-file
在此示例中,您将学习使用fprintf()语句在文件中写一个句子。
要理解此示例,您应该了解以下 C 编程主题:
该程序将用户输入的句子存储在文件中。
#include <stdio.h>#include <stdlib.h>int main() {char sentence[1000];// creating file pointer to work with filesFILE *fptr;// opening file in writing modefptr = fopen("program.txt", "w");// exiting programif (fptr == NULL) {printf("Error!");exit(1);}printf("Enter a sentence:\n");fgets(sentence, sizeof(sentence), stdin);fprintf(fptr, "%s", sentence);fclose(fptr);return 0;}
输出
Enter a sentence: C Programming is funHere, a file named program.txt is created. The file will contain C programming is fun text.
在程序中,用户输入的句子存储在sentence变量中。
然后,以写入模式打开名为program.txt的文件。 如果文件不存在,将创建它。
最后,将使用fprintf()函数将用户输入的字符串写入此文件,并关闭文件。
