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

來源:互聯網
上載者:User

 #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 */
  • 聯繫我們

    該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

    如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.