1. gets
gets函数的头文件是<stdio.h>,原型如下:
char *gets(char *s);
gets从stdin中读入一行内容到s指定的buffer中,当遇到换行符或EOF时读取结束。读取成功时,返回s地址;失败时返回null。需要注意的是,gets会将行末尾的'\n'字符或EOF替换成'\0',这样,gets读取的内容中不包括'\n'字符。如果要获取读取字符串的长度,可以调用strlen函数获得。
1.#include <stdio.h>
2.#include <stdlib.h>
3.#include <string.h>
4.
5.int main()
6.{
7. int size = 1024;
8. char* buff = (char*)malloc(size);
9.
10. // read lines
11. while(NULL != gets(buff)){
12. printf("Read line with len: %d\n", strlen(buff));
13. printf("%s", buff);
14. }
15.
16. // free buff
17. free(buff);
18.}
2. fgets
fgets函数的头文件是<stdio.h>,原型如下:
char *fgets(char *s, int size, FILE*stream);
fgets从stream中读取最多size-1大小的内容到s指定的buffer中,当遇到换行符或EOF时读取结束。读取成功时,返回s地址;失败时返回null。需要注意的是,fgets会在所读取的内容后面添加'\0',这样,fgets读取的内容中会包括行末尾的'\n'字符。如果要获取读取字符串的长度,可以调用strlen函数获得。
1.#include <stdio.h>
2.#include <stdlib.h>
3.#include <string.h>
4.
5.int main()
6.{
7. int size = 1024;
8. char* buff = (char*)malloc(size);
9.
10. // read lines
11. while(NULL != fgets(buff, size, stdin)){
12. printf("Read line with len: %d\n", strlen(buff));
13. printf("%s", buff);
14. }
15. // free buff
16. free(buff);
}
3.
3. getline
getline函数的头文件是<stdio.h>,原型如下:
ssize_t getline(char **lineptr,size_t *n, FILE *stream);
getline从stream中读取一行内容到*lineptr所指定的buffer中,当遇到换行符或EOF时读取结束。*n是*lineptr所指定的buffer的大小,如果*n小于读入的内容长度,getline会自动扩展buffer长度,并更新*lineptr和*n的值。读取成功时,返回读入的字符个数;失败时返回-1。需要注意的是,gelines读取的内容中会包括行末尾的'\n'字符。
1.#include <stdio.h>
2.#include <stdlib.h>
3.
4.int
5.main(void)
6.{
7. char *line = NULL;
8. size_t len = 0;
9. ssize_t read;
10.
11. while ((read = getline(&line, &len, stdin)) != -1) {
12. printf("Retrieved line of length %zu, %u :\n", read, len);
13. printf("%s", line);
14. }
15.
16. free(line);
17. exit(EXIT_SUCCESS);
18.}
1. 自己实现my_getline
可以自己实现,原型如下:
int my_getline(char* line, intmax_size);
my_getline从stdin中读取最多max_size-1个字符到line所指定的buff中,当遇到换行符或EOF时读取结束。读取成功时,返回读取的字符串长度;失败时返回0。my_getline读取的内容中会包括行末尾的'\n'字符。
1.#include <stdio.h>
2.#include <stdlib.h>
3.
4.int my_getline(char* line, int max_size)
5.{
6. int c;
7. int len = 0;
8. while( (c = getchar()) != EOF && len < max_size ){
9. line[len++] = c;
10. if('\n' == c)
11. break;
12. }
13.
14.
15. line[len] = '\0';
16. return len;
17.}
18.
19.int main()
20.{
21. int max_size = 1024;
22. char* buff = (char*)malloc( sizeof(char) * max_size );
23.
24. //getline
25. int len;
26. while(0 != (len = my_getline(buff, max_size))){
27. printf("Read line with len: %d\n", len);
28. printf("%s", buff);
29. }
30.
31. free(buff);
32.}