首页 > 技术文章 > fgets读取文件时的注意事项

or2- 2016-10-06 15:25 原文

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算有效长度里元素

推荐阅读