博学而笃志 切问而近思 仁在其中
详情
C语言fputs()和fgets()函数
作者:--     发布时间:2019-11-20     评论:0     阅读:0

在c语言编程中,fputs()fgets()函数用于从流中写入和读取字符串。下面来看看看如何使用fgets()fgets()函数写和读文件的例子。

写文件:fputs()函数

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

fputs()函数的语法:

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

示例:

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

#include<stdio.h>  
void main() {
    file *fp;

    fp = fopen("myfile2.txt", "w");
    fputs("hello c programming \n", fp);
    fputs("h3 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 
h3 tutorials c programming

读取文件:fgets()函数

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

语法:

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

示例:

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

#include<stdio.h>  

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 
h3 tutorials c programming


下一篇:测试
相关文章
loading......
最新动态
所有评论

loading......

网站声明:
本站部分内容来自网络,如您发现本站内容
侵害到您的利益,请联系本站管理员处理。
联系站长
373515719@qq.com
关于本站:
编程参考手册