fgets讀取檔案時的注意事項

c3tc3tc3t發表於2016-10-06

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算有效長度裡元素

相關文章