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

在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("zaixian 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 
zaixian 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 
zaixian tutorials c programming

上一篇: C语言fputc()和fgetc()函数 下一篇: C语言fseek()函数