2011-12-21 31 views
1

我需要在ANSI C中打開文件,將其所有行讀入動態分配的字符串數組,並打印前四行。該文件可以是最大2^31-1個字節的任何大小,而每行最多16個字符。我有以下,但它似乎並沒有工作:如何將文件中的行保存到動態數組中並打印?

#define BUFSIZE 1024 
char **arr_lines; 
char buf_file[BUFSIZE], buf_line[16]; 
int num_lines = 0; 
// open file 
FILE *fp = fopen("file.txt", "r"); 
if (fp == NULL) { 
    printf("Error opening file.\n"); 
    return -1; 
} 
// get number of lines; from http://stackoverflow.com/a/3837983 
while (fgets(buf_file, BUFSIZE, fp)) 
    if (!(strlen(buf_file) == BUFSIZE-1 && buf_file[BUFSIZE-2] != '\n')) 
     num_lines++; 
// allocate memory 
(*arr_lines) = (char*)malloc(num_lines * 16 * sizeof(char)); 
// read lines 
rewind(fp); 
num_lines = 0; 
while (!feof(fp)) { 
    fscanf(fp, "%s", buf_line); 
    strcpy(arr_lines[num_lines], buf_line); 
    num_lines++; 
} 
// print first four lines 
printf("%s\n%s\n%s\n%s\n", arr_lines[0], arr_lines[1], arr_lines[2], arr_lines[3]); 
// finish 
fclose(fp); 

我有關於如何才能確定arr_lines麻煩寫入這一點,並輕鬆地訪問它的元素。

+0

作爲一個開始,不要施放malloc的結果,請參閱http://stackoverflow.com/questions/605845/do-i-cast-the-result-of-malloc。其次,發佈一個完整的最小程序,編譯該程序,展示您遇到的問題... – 2011-12-21 20:21:59

回答

0

變化

(*arr_lines) = (char*)malloc(num_lines * 16 * sizeof(char)); 

arr_lines = malloc(num_lines * sizeof(char*)); 

然後在它下面的while循環,增加

arr_lines[n] = malloc(16 * sizeof(char)); 
3

有代碼中的一些問題,但最主要的是在malloc行中,您正在取消引用未初始化的指針。另外,除非你的行由單個單詞組成,否則你應該使用fgets()而不是fscanf(...%s ...),因爲後者在讀取一個單詞而不是一行後返回。即使你的文字是文字,但使用相同類型的循環也是比較安全的,無論如何你都用它來計算行數,否則你的閱讀風險會超過你分配的行數。

#include <stdio.h> 
#include <stdlib.h> 
#include <string.h> 
int main(void){ 
#define LINESIZE 16 
     char *arr_lines, *line; 
     char buf_line[LINESIZE]; 
     int num_lines = 0; 
     // open file 
     FILE *fp = fopen("file.txt", "r"); 
     if (fp == NULL) { 
       printf("Error opening file.\n"); 
       return -1; 
     } 
     // get number of lines; from http://stackoverflow.com/a/3837983 
     while (fgets(buf_line, LINESIZE, fp)) 
       if (!(strlen(buf_line) == LINESIZE-1 && buf_line[LINESIZE-2] != '\n')) 
         num_lines++; 
     // allocate memory 
     arr_lines = (char*)malloc(num_lines * 16 * sizeof(char)); 
     // read lines 
     rewind(fp); 
     num_lines = 0; 
     line=arr_lines; 
     while (fgets(line, LINESIZE, fp)) 
       if (!(strlen(line) == LINESIZE-1 && line[LINESIZE-2] != '\n')) 
         line += LINESIZE; 
     // print first four lines 
     printf("%s\n%s\n%s\n%s\n", &arr_lines[16*0], &arr_lines[16*1], &arr_lines[16*2], &arr_lines[16*3]); 
     // finish 
     fclose(fp); 
     return 0; 
} 

希望這有助於!

相關問題