LINUX C實現讀取一個文本文件並返回其中最長的行的內容

 #include <stdio.h>

   2 #include "lines.h"    3 #include <stdlib.h>    4    5 char *readLines(const char *file, size_t *longest) //file 文件名    6 {    7    FILE *fp;     8    char *p;    9    char ch;   10    int log=0,i=0,lg=1,j=1; //最長 i表示個數 j表示第幾行 lg表示第幾行   11    if((fp=fopen(file,"r"))==NULL) // open file   12    {   13       *longest=0;   14       return NULL;   15    }   16    while((ch=fgetc(fp))!=EOF) //判斷文件是否結束   17    {   18       if(ch=='/n')   19       {   20           if(log<i)   21           {   22              log=i;   23              lg=j;   24           }   25           j++;   26           i=0;       27       }   28       else   29       {   30          i++;   31       }   32    }   33 //目前確定了長度 和 第幾行   34 //printf("log=%d lg=%d/n",log,lg);   35 if(log==0)   36 {   37     *longest=0;   38     p=NULL;   39 }   40 else   41 {   42    p=(char *)malloc(sizeof(char)*log);   43    *longest=log;   44    rewind(fp);   45    i=0;   46    while((ch=fgetc(fp))!=EOF && log>0)   47    {   48         if(lg==1)   49         {   50            p[i++]=ch;   51            log--;                52         }   53         else   54         {   55           if(ch=='/n')   56           {   57              lg--;   58           }   59         }   60    }   61   }   62    fclose(fp);   63    return p;   64 }   65 /*   66 int main()   67 {   68   size_t b=0;   69   char *e;   70   int i;   71   e=readLines("/root/kt/unit5/U5E1/jjk.txt",&b);   72   for(i=0;i<b;i++)   73   putchar(*(e+i));   74   printf("b=%u",b);   75   return 0;   76 }   77 */
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章