C語言讀取文件所有內容

  • 2019 年 12 月 19 日
  • 筆記

#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);//輸出字符串p      return 0;  }

本文為仙士可原創文章,轉載無需和我聯繫,但請註明來自仙士可博客www.php20.cn