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