fgetc,fgets,getline用法

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;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值