该程序将用户输入的句子存储在文件中。
#include <stdio.h> #include <stdlib.h> int main() { char sentence[1000]; // creating file pointer to work with files FILE *fptr; // opening file in writing mode fptr = fopen("program.txt", "w"); // exiting program if (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 fun Here, a file named program.txt is created. The file will contain C programming is fun text.
在程序中,用户输入的句子存储在
sentence变量中。
然后,一个名为program.txt 的文件以写入方式打开。如果文件不存在,它将被创建。
最后,将使用
fprintf()
函数将用户输入的字符串写入此文件并关闭文件。