


举例:
创建一个文件,并向其中写入小写字母a到z,然后关闭文件。接着再以读的形式打开这个文件,并将这些字符输出到终端。
#include<stdio.h>
int main()
{
// 向文件中输入数据
FILE* pf = fopen("text.txt", "w");
if (pf == NULL)
{
perror("fopen :w");
return 1;
}
else
{
char ch = 0;
for (ch = 'a'; ch <= 'z'; ch++)
{
fputc(ch, pf);
}
}
fclose(pf);
pf = NULL;
// 向文件中读取数据
FILE* pf2 = fopen("text.txt", "r");
if (pf2 == NULL)
{
perror("fopen: r");
return 1;
}
else
{
int ch = 0; // ch 为int类型,以便接收fgetc的返回值
while ((ch = fgetc(pf2)) != EOF)
{
putchar(ch); // 直接输出字符
}
}
fclose(pf2);
pf2 = NULL;
return 0;
}
举例:
text.txt拼接之前的值

#include <stdio.h>
int main()
{
FILE* pFile;
char sentence[256];
printf("Enter sentence to append: ");
fgets(sentence, 256, stdin);
pFile = fopen("text.txt", "a");
fputs(sentence, pFile);
fclose(pFile);
return 0;
}输入:

text.txt拼接后:


从流中读取字符,并将它们作为字符串存储到 str 中,直到读取 (num-1) 个字符(第num个字符会被自动读成‘\0’)或到达换行符或文件末尾,以先发生者为准。
换行符‘\n’ 使 fgets 停止读取,但它被函数视为有效字符,并包含在复制的字符串中。
空字符会自动附加到 str 的字符之后。
fgets 与 gets 有很大不同:fgets 不仅接受流参数,还允许指定 str 的最大大小,并在字符串中包含任何结束换行符。
#include <stdio.h>
int main()
{
FILE* pFile;
char my_string[100];
pFile = fopen("myfile.txt", "r");
if (pFile == NULL) perror("Error opening file");
else
{
if (fgets(my_string, 100, pFile) != NULL)
puts(my_string);
fclose(pFile);
}
return 0;
}