C/C++逐行读取文本文件的数据
C++:
函数声明:
ssize_t getline(char **lineptr, size_t *n, FILE *stream);
成功,则返回(有符号整型)每行的字节数,包含结束符;否则返回-1
例子:
#include<iostream> #include<stdio.h> #include<unistd.h> #include<dirent.h> #include<stdlib.h> #include<errno.h> #include<malloc.h> using namespace std; #define FILE_PATH "/home/tmp/test/test.txt" #define BUFF_LEN 256 int main() { FILE *fp = NULL; char *file = FILE_PATH; char *line = NULL; size_t line_len = BUFF_LEN; int len = 0; if( (0!=access(file,R_OK|F_OK)) || (NULL==(fp=fopen(file,"r"))) ) { printf("open %s failed, errno=%d\n",file,errno); return -1; } while( (len=getline(&line,&line_len,fp))>0 )//逐行读取,如果line为NULL,则系统会自动malloc,所以用完记得free { printf("the content of each line is:\n%s",line); printf("the length of each line is: %d\n\n",len); } if(fp != NULL) { fclose(fp); fp = NULL; } if(line) { free(line); //记得释放资源 } return 0; }
C语言:
char *fgets(char *buf, int bufsize, FILE *stream);
成功,则返回第一个参数buf;否则返回NULL
例子:
#include<stdio.h> #include<stdlib.h> #include<unistd.h> #include<malloc.h> #define FILE_PATH "/home/tmp/test/test.txt" #define BUFF_LEN 256 int main() { FILE *fp = NULL; char *file = FILE_PATH; char *line = (char *)malloc(BUFF_LEN * sizeof(char));//和C++不同的是,事先要申请空间,否则报段错误 if( (0 != access(file,R_OK|F_OK)) || (NULL==(fp=fopen(file,"r"))) ) { printf("open %s failed\n",file); return -1; } while( fgets(line, BUFF_LEN, fp) != NULL )//逐行读取数据 { printf("the content of each line is:\n%s",line); //fgets本身已经读入了换行符,所以打印时不用%s\n,要不然读取的每行之间会多换一行 } if(fp!=NULL) { fclose(fp); } return 0; }