示例
//Visual Studio中加上这句才可以使用scanf()
//否则只能使用scanf_s()
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <string.h>
#include <ctype.h>
//malloc()、free()
#include <stdlib.h>
#include <time.h>
#include <math.h>
#define MAX 41
//argc: 参数个数 argv[]: 参数数组
//int main(int argc, char **argv)
int main(int argc, char *argv[])
{
FILE *fp;
char words[MAX];
if ((fp = fopen("test.txt", "w+")) == NULL)
{
fprintf(stderr, "can't open file");
exit(EXIT_FAILURE);
}
puts("Enter words to add to the file; press the #");
while ((fscanf(stdin, "%40s", words) == 1) && (words[0] != '#'))
fputs(words, fp);//fputs()向文件中写入字符串时不会自动加换行符
puts("File contents:");
rewind(fp); // 返回到文件开始处
//从文件指针中读取1个单词存放到words中
//fgets()函数读取输入直到第1个换行符的后面,或读取文件结尾,或者读取MAX-1个字符
//然后,fgets()在末尾添加一个空字符使之成为一个字符串。
//fgets()在遇到EOF时将返回NULL,否则返回之前传给它的地址
while (fgets(words, MAX, fp) != NULL)
puts(words);
puts("Done!");
if(fclose(fp) != 0)
fprintf(stderr, "Error closing file\n");
/*
fgets()会保留换行符,所以fputs()不会再添加换行符。
*/
system("pause");
return 0;
}
运行测试