我需要在 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
以写入此内容并轻松访问其元素时遇到了麻烦。