1. 程式人生 > 實用技巧 >C語言 自定義函式按行讀入檔案

C語言 自定義函式按行讀入檔案

在之前的部落格中 https://www.cnblogs.com/mmtinfo/p/13036039.html 讀取一行的getline()函式是GNU 的擴充套件函式。

這裡用自定義函式實現這個功能,從檔案中讀取整行,不論一行多長,動態分配記憶體。

 1 #include <stdlib.h>
 2 #include <stdio.h>
 3 #include <string.h>
 4 
 5 char *readLine(FILE *file){
 6     if(file == NULL){
 7         exit(1);
 8     }
 9     /*
malloc linebuffer */ 10 int baseLen = 256; // 初始長度設定256字元 11 char *lineBuf = (char *)malloc(sizeof(char) * baseLen); 12 if(lineBuf == NULL){ 13 exit(1); 14 } 15 16 int ch,index=0; 17 while((ch=fgetc(file)) != 10 && ch != EOF){ // ASCII 10 => "\n" 18 lineBuf[index] = ch;
19 index++; 20 21 if(index == baseLen){ 22 baseLen += 256; 23 lineBuf = (char *)realloc(lineBuf, baseLen); // 記憶體不足時每次再重新分配256字元空間 24 if(lineBuf == NULL){ 25 exit(1); 26 } 27 } 28 } 29 lineBuf[index] = '\0'; //
end of string add '\0' 30 31 return lineBuf; 32 } 33 34 int main(int argc, char *argv[]) 35 { 36 FILE *fp = fopen(argv[1],"r"); 37 if(fp == NULL){ 38 exit(1); 39 } 40 while(!feof(fp)){ 41 char *line = readLine(fp); 42 printf("%s\n",line); 43 } 44 exit(0); 45 }

注:目前還有一點小問題,行內容輸出的時候最後回多一個換行。