C语言读取文件所有内容
转载1:原文链接
转载2:原文链接
关键是获取文件大小
- 首先使用fseek()定位到文件末尾
- ftell()计算当前文件位置指针相对于文件首的偏移字节数,也就是文件的大小
- 用rewind()重新定位到文件开头位置
- 将每次读取的字符串拼接或直接一次性读取所有字符串
方法1
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
char *getfileall(char *fname)
{
FILE *fp;
char *str;
char txt[1000];
int filesize;
if ((fp=fopen(fname,"r"))==NULL){
printf("打开文件%s错误\n",fname);
return NULL;
}
fseek(fp,0,SEEK_END);
filesize = ftell(fp);
str=(char *)malloc(filesize);
str[0]=0;
rewind(fp);
while((fgets(txt,1000,fp))!=NULL){
strcat(str,txt);
}
fclose(fp);
return str;
}
int main(int argc, char *argv[])
{
char *p;
char *fname="/tmp/test.txt";
p=getfileall(fname);
if (p!=NULL) puts(p);
return 0;
}
方法2:
char * ReadFile(char * path, int *length)
{
FILE * pfile;
char * data;
pfile = fopen(path, "rb");
if (pfile == NULL)
{
return NULL;
}
fseek(pfile, 0, SEEK_END);
*length = ftell(pfile);
data = (char *)malloc((*length + 1) * sizeof(char));
rewind(pfile);
*length = fread(data, 1, *length, pfile);
data[*length] = '\0';
fclose(pfile);
return data;
}