在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("%sn%sn%sn%sn", arr_lines[0], arr_lines[1], arr_lines[2], arr_lines[3]);
// finish
fclose(fp);
我在如何定义arr_lines
以便写入此并轻松访问其元素方面遇到了麻烦。
您的代码中存在一些问题,但主要问题是在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("%sn%sn%sn%sn", &arr_lines[16*0], &arr_lines[16*1], &arr_lines[16*2], &arr_lines[16*3]);
// finish
fclose(fp);
return 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));