首页 > 代码库 > fgets读取文件时的注意事项
fgets读取文件时的注意事项
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个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。