C++:
函数声明:
ssize_t getline(char **lineptr, size_t *n, file *stream);
成功,则返回(有符号整型)每行的字节数,包含结束符;否则返回-1
例子:
#include<iostream>
#include<;
#include<uni;
#include<dirent.h>
#include<;
#include<errno.h>
#include<malloc.h>
usingnamespace std;
#define FILE_PATH "/home/tmp/te;
#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<;
#include<;
#include<uni;
#include<malloc.h>
#define FILE_PATH "/home/tmp/te;
#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);
}
if(fp!=NULL)
{
fclose(fp);
}
return 0;
}