c语言编程w3s,fputs 和fgets 函数

C语言 的 fputs 和fgets 函数

在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.txt\n");

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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值