fgetc,fgets,getline用法

2023-05-16

Linux(Ubuntu)下用法

在Ubuntu下shell中,man fgets可以看到fgetc, fgets等用法,man getline可以看到getline用法。

#include <stdio.h>
int fgetc(FILE *stream);
char *fgets(char *s, int size, FILE *stream);
ssize_t getline(char **lineptr, size_t *n, FILE *stream);

按照用法说明,编写测试用例如下:

/*
 * fgetc1.c
 * shows how to use fgetc
 */

#include <stdio.h>

int main()
{
    int ch;
    while ((ch = fgetc(stdin)) != EOF) {
        printf("%c\n", ch);
    }

    return 0;
}
/*
 * fgets1.c
 * shows how to use fgets
 */

#include <stdio.h>

int main(int ac, char *av[])
{   
    const int csize = 10;
    char buffer[csize];

    while (fgets(buffer, csize, stdin) != NULL) {
       printf("%s\n", buffer);
    }   

    return 0;
}

测试用例getline1.c和getline2.c分别从标准输入流和文件流读取一行。

/*
 * getline1.c
 * shows how to use getline
 */


#include <stdio.h>

int main(int ac, char *av[])
{
    size_t size = 0;
    const int csize = 100;
    char *buffer;
    ssize_t read;

    while ((read = getline(&buffer, &size, stdin)) != -1) {
            printf("%s", buffer);
    }

    return 0;
}
/*
 * getline2.c
 * shows how to get line from files
 */

#include <stdio.h>

int main()
{
    FILE *fp;
    size_t size = 0;
    ssize_t read;
    char *buffer;
    char *filename = "/home/cheewing/Documents/ULPP/mytest/getlinefile.dat";

    if ((fp = fopen(filename, "r")) == NULL) 
            perror("open file \n");

    while ((read = getline(&buffer, &size, fp)) != -1) {
            printf("%s\n", buffer);
    }

    fclose(fp);

    return 0;
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

fgetc,fgets,getline用法 的相关文章

  • ViewBinding绑定布局

    最近这段时间在学习Kotlin xff0c 突然发现谷歌已经把kotlin android extensions插件废弃 xff0c 目前推荐使用ViewBinding来进行替代 xff0c 接下来通过本文给大家分享Android使用Vie

随机推荐