美文网首页
关于 C 语言中使用库函数 fgets 读取文件的使用方法

关于 C 语言中使用库函数 fgets 读取文件的使用方法

作者: 蓝天白云bubble | 来源:发表于2020-11-15 17:26 被阅读0次

           
    简书著作权归作者所有,任何形式的转载都请联系作者获得授权并注明出处。

    fgets 函数

    #include <stdio.h>
    char *fgets(char *s, int size, FILE *stream);
    

    各参数的意义:

    s: 字符型指针,指向存储读入数据的缓冲区的地址
    size: 从流中读入 size - 1 个字符,第 size 个字符是 '\0'
    stream: 指向读取的流

    返回值

    如果读入成功,则返回其第一个参数 s
    如果读入错误或遇到文件结尾(EOF),则返回NULL

    fgets 函数读取文件时的工作原理

    fgets 执行时会从文件流的当前位置读取 size - 1 个字符,然后在读取到的这些字符后面添加一个 '\0' 字符并将这些字符放入 s 中。如果 fgets 在执行时发现文件流的当前位置到换行符或文件末尾之间的这些字符不够 size - 1 个字符,则将不够数的字符统统用 '\0' 代替。

    fgets 函数读取文件的一般使用

    1、新建文件 doc.txt,并在文件中输入以下内容:

    Once there were two friends Kanakaksha the owl and Sumitra the swan. Sumitra was the king of the swans. But Kanakaksha was an ordinary owl. He was afraid to let Sumitra know that he was a poor owl. So he told Sumitra that he was also a king and also had subjects. Everyday the owl would fly to the pond where the swan lived. 
    
    One day as usual, Kanakaksha flew to the pond to meet his friend. “Good morning Sumitra, how are you today?" he asked.
    

    2、新建文件 test.c,并在文件中输入以下内容:

    #include <stdio.h>
    #include <stdlib.h>
    
    int main(int argc, char **argv) {
        char *file_name = "/home/jason/Desktop/doc.txt";
        FILE *fp;
        if ((fp = fopen(file_name, "r")) == NULL) {
            perror(file_name);
            exit(1);
        }
    
        char buff[5] = {0};
        while (fgets(buff, sizeof(buff), fp) != NULL) {
            printf("%s", buff);
        }
        return 0;
    }
    

    执行如下命令进行编译:

    gcc test.c -o test
    

    运行命令:

    ./test
    

    得到结果如下:

    Once there were two friends Kanakaksha the owl and Sumitra the swan. Sumitra was the king of the swans. But Kanakaksha was an ordinary owl. He was afraid to let Sumitra know that he was a poor owl. So he told Sumitra that he was also a king and also had subjects. Everyday the owl would fly to the pond where the swan lived.
    
    One day as usual, Kanakaksha flew to the pond to meet his friend. “Good morning Sumitra, how are you today?" he asked.
    

    相关文章

      网友评论

          本文标题:关于 C 语言中使用库函数 fgets 读取文件的使用方法

          本文链接:https://www.haomeiwen.com/subject/dpwnbktx.html