分享

C语言fputs()和fgets()函数

 C语言与CPP编程 2021-12-15

在C语言编程中,fputs()和fgets()函数用于从流中写入和读取字符串。

下面来看看看如何使用fgets()和fgets()函数写和读文件。

写文件:fputs()函数 fputs()函数将一行字符串写入文件,它将字符串输出到流。

其行为方式如下:

(1)遇到换行或文件结束EOF则返回。

(2)按行读取。

(3)每一行结束处的换行字符'/n’也算该行字符。

(4)对于大小为size的buf,最多只读取size-1个字符。

(5)自动地把buf中最后一个字符(通常是换行符)的后面一个字节填充零结束符('/0')。

fputs()函数的语法:

int fputs(const char *s, FILE *stream)

示例:创建一个源文件:fputs-write-file.c,其源代码如下 -

#include<stdio.h>//20200427void main() {FILE *fp;fp = fopen("my-write-file.txt""w");fputs("hello c programming \n", fp);fputs("performance c programming \n", fp);printf("all content had write to file: my-write-file.txt\n");fclose(fp);}
执行上面示例代码,得到以下结果 :
all content had write to file: my-write-file.txt
执行上面代码后,打开文件:my-write-file.txt,应该会看到以下内容 -
hello c programmingperformance c programming

读取文件:fgets()函数 fgets()函数从文件中读取一行字符串,它从流中获取字符串。

其行为方式如下:

(1)把str中零结束符之前的全部文字输入到文件中。

(2)输入完成后,不会增加额外的特殊字符,如换行符等。

语法:

char* fgets(char *s, int n, FILE *stream)

示例:创建一个源文件:fgets-read-file.c,其代码如下所示 :

#include<stdio.h>//20200427void main() { FILE *fp; char text[300]; fp = fopen("my-write-file.txt", "r"); printf("%s", fgets(text, 200, fp)); // 第一行 printf("%s", fgets(text, 200, fp)); // 第二行 fclose(fp);}
执行上面示例代码,得到以下结果:
hello c programmingperformance c programming

    转藏 分享 献花(0

    0条评论

    发表

    请遵守用户 评论公约

    类似文章 更多