C语言fgets读取整个文本文件的内容

时间:2023-02-11 07:45:22
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int test_fgets(const char* filePath)
{

FILE* fp=fopen(filePath,"r");
if(fp==NULL)
{
printf("open error!%s",strerror(errno));
return -1;
}
char buffer[2048]={0};
while(fgets(buffer,sizeof(buffer),fp))
{
printf("%s",buffer);
}
fclose(fp);
return 0;
}

char* getAllFileData2(char *filePath)
{
FILE *fp;
char *str;
char buffer[4096];
int filesize;
if ((fp=fopen(filePath,"r"))==NULL){
printf("打开文件%s错误 error=%s \n",filePath,strerror(errno));
return NULL;
}

fseek(fp,0,SEEK_END);
filesize = ftell(fp);
str=(char *)malloc(filesize+1);
memset(str,0,filesize+1);
rewind(fp);
int bufsize=sizeof(buffer);
//fgets的缓存大小只能为bufsize? 如果一个行数据很长怎么办?
while((fgets(buffer,bufsize,fp))!=NULL){ //每次最多读取bufsize-1个字符
strcat(str,buffer);
}
fclose(fp);
return str;
}

char* getAllFileData(char *filePath)
{
FILE *fp;
char *str;
char buffer[4096];
int filesize;
if ((fp=fopen(filePath,"r"))==NULL){
printf("打开文件%s错误 error=%s \n",filePath,strerror(errno));
return NULL;
}

fseek(fp,0,SEEK_END);
filesize = ftell(fp);
str=(char *)malloc(filesize+1);
memset(str,0,filesize+1);
rewind(fp);
int bufsize=sizeof(buffer);
//fgets函数成功将返回buf,失败或读到文件结尾返回NULL。因此我们不能直接通过fgets的返回值来判断函数是否是出错而终止的,应该借助feof函数或者ferror函数来判断。
while(!feof(fp)){
fgets(buffer,bufsize,fp);
strcat(str,buffer);
}
fclose(fp);
return str;
}


int main(void)
{
test_fgets("d:/test.txt");

printf("=====================================\n");
char *p;
p=getAllFileData("d:/test.txt");
if (p!=NULL)
{
puts(p);
free(p);
}
return 0;
}