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;
}