1000字范文,内容丰富有趣,学习的好帮手!
1000字范文 > C语言读取文件所有内容

C语言读取文件所有内容

时间:2022-12-27 11:02:06

相关推荐

C语言读取文件所有内容

C语言读取文件所有内容

转载1:原文链接

转载2:原文链接

关键是获取文件大小

首先使用fseek()定位到文件末尾ftell()计算当前文件位置指针相对于文件首的偏移字节数,也就是文件的大小用rewind()重新定位到文件开头位置将每次读取的字符串拼接或直接一次性读取所有字符串

方法1

#include<stdio.h>#include<stdlib.h>#include<string.h>//函数返回fname指定文件的全部内容,如果打不开文件,则返回NULL,并显示打开文件错误 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);//通过ftell函数获得指针到文件头的偏移字节数。str=(char *)malloc(filesize);//动态分配str内存// str=malloc(filesize);//动态分配str内存str[0]=0;//字符串置空// memset(str,filesize*sizeof(char),0);//清空数组,字符串置空第二种用法rewind(fp);while((fgets(txt,1000,fp))!=NULL){//循环读取1000字节,如果没有数据则退出循环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);//输出字符串preturn 0;}

方法2:

/*** 读取文件内容* path:文件路径* length:文件大小(out)* return:文件内容*/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;}

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。