fgets讀取檔案時的注意事項

來源:互聯網
上載者:User

標籤:

1 文字檔 a.txt 內容如下


 
2 c代碼
  FILE *fil;    if (!(fil = fopen("/home/rudy/projects/paser/a.txt", "rb"))) {        printf("File I/O error,the File is not exist\n");        exit(0);    } int line = 0;    while(!feof(fil)) {        if (fgetc(fil) == ‘\n‘) {            ++line;        }    }    ++line;    fclose(fil);    if (!(fil = fopen("/home/rudy/projects/paser/a.txt", "rb"))) {        printf("File I/O error,the File is not exist\n");        exit(0);    }    char ** all =(char **) malloc( line * sizeof(char *));    for (int iCurrLineIndex = 0; iCurrLineIndex < line; ++iCurrLineIndex) {        all[iCurrLineIndex] = (char *) malloc(20 );        fgets(all[iCurrLineIndex], 21, fil);    } for (int iCurrLineIndex = 0; iCurrLineIndex < line; ++iCurrLineIndex) {        printf("this is len = %d \n",strlen(all[iCurrLineIndex]));        for(int i = 0;i <11;i++) {            if (all[iCurrLineIndex][i] == ‘\0‘)            {                printf("%s\n ","this is 0");            }else if ( all[iCurrLineIndex][i]== ‘\n‘)            {                printf("%s\n ","this is n");            }else{                printf("%c ",all[iCurrLineIndex][i]);            }        }        printf("\n");    }

輸出結果

 

this is len = 10 1 2 3 4 5 6 7 8 9 this is n this is 0 this is len = 10 a b c d e f g h i this is n this is 0 this is len = 9 1 2 3 4 5 6 7 8 9 this is 0 this is 0

總結: fgets讀取時,如果指定的讀取大小,小於實際行大小 那麼 不添加\n做結尾,使用\0 ,然後接著讀取沒讀完的當前行資料作為新的一行開始

    fgets讀取時,如果指定讀取大小.大於實際行大小,那麼將\n添加到末端.再添加\0

   \0不算做有效長度裡的元素,\n算有效長度裡元素

fgets讀取檔案時的注意事項

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.