从不定长文本中读取整行,输出最后会多出一个空行问题
如何避免输出最后的空行程序代码:
#include <stdlib.h> #include <stdio.h> #include <string.h> char *readLine(FILE *file){ if(file == NULL){ exit(1); } /* malloc linebuffer */ int baseLen = 256; // 初始长度设置256字符 char *lineBuf = (char *)malloc(sizeof(char) * baseLen); if(lineBuf == NULL){ exit(1); } int ch,index=0; while((ch=fgetc(file)) != 10 && ch != EOF){ // ASCII 10 => "\n" lineBuf[index] = ch; index++; if(index == baseLen){ baseLen += 256; lineBuf = (char *)realloc(lineBuf, baseLen); // 内存不足时每次再重新分配256字符空间 if(lineBuf == NULL){ exit(1); } } } lineBuf[index] = '\0'; // end of string add '\0' return lineBuf; } int main(int argc, char *argv[]) { FILE *fp = fopen(argv[1],"r"); if(fp == NULL){ exit(1); } while(!feof(fp)){ char *line = readLine(fp); printf("%s\n",line); } exit(0); }