在C语言编程中,fputs()和fgets()函数用于从流中写入和读取字符串。下面来看看看如何使用fgets()和fgets()函数写和读文件的例子。
写文件:fputs()函数
fputs()函数将一行字符串写入文件,它将字符串输出到流。
fputs()函数的语法:
int fputs(const char *s, FILE *stream)
示例:
创建一个源文件:fputs-write-file.c,其源代码如下 –
#include void main() { FILE *fp; fp = fopen("myfile2.txt", "w"); fputs("hello c programming n", fp); fputs("yiibai tutorials c programming n", fp); printf("all content had write to file: myfile2.txtn"); fclose(fp); }
执行上面示例代码,得到以下结果 –
all content had write to file: myfile2.txt
执行上面代码后,打开文件:myfile2.txt,应该会看到以下内容 –
hello c programming yiibai tutorials c programming
读取文件:fgets()函数
fgets()函数从文件中读取一行字符串,它从流中获取字符串。
语法:
char* fgets(char *s, int n, FILE *stream)
示例:
创建一个源文件:fgets-read-file.c,其代码如下所示 –
#include void main() { FILE *fp; char text[300]; fp = fopen("myfile2.txt", "r"); printf("%s", fgets(text, 200, fp)); // 第一行 printf("%s", fgets(text, 200, fp)); // 第二行 fclose(fp); }
执行上面示例代码,得到以下结果 –
hello c programming yiibai tutorials c programming
¥ 我要打赏 纠错/补充 收藏