我需要在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
麻煩寫入這一點,並輕鬆地訪問它的元素。
作爲一個開始,不要施放malloc的結果,請參閱http://stackoverflow.com/questions/605845/do-i-cast-the-result-of-malloc。其次,發佈一個完整的最小程序,編譯該程序,展示您遇到的問題... – 2011-12-21 20:21:59