从文件中读取行并将它们存储在数组中 [英] Reading lines from a file and storing them in an array
问题描述
我无法逐行从文件中读取文本并将每行存储到数组中.然后,我需要打印出我得到的数组.
I am having trouble reading text from a file line by line and storing each line into an array. I then need to print out the array that I get.
我不确定是否为该数组正确分配了空间.我在 read_one_line()
函数中的 fgets()
遇到了分段错误.
I'm not sure if I correctly allocated space for this array. And I'm getting a segmentation fault coming from the fgets()
in my read_one_line()
function.
我的代码:
#include <stdio.h>
#include <stdlib.h>
char* read_one_line(FILE* fp, char* line);
char* allocate_mem(FILE* fp, char* line);
void print_lines(char** lines, int num_lines){
int i;
for(i = 0 ; i < num_lines; ++i){
printf("%d. %s", i+1, lines[i]);
}
}
void free_lines(char** lines, int num_lines){
int i;
for(i = 0 ; i < num_lines; ++i){
free(lines[i]);
}
if(lines != NULL && num_lines > 0){
free(lines);
}
}
FILE* validate_input(int argc, char* argv[]){
FILE* fp = NULL;
if(argc < 2){
printf("Not enough arguments entered.\nEnding program.\n");
exit(0);
}
else if(argc > 2){
printf("Too many arguments entered.\nEnding program.\n");
exit(0);
}
fp = fopen(argv[1], "r");
if(fp == NULL){
printf("Unable to open file: %s\nEnding program.\n", argv[1]);
exit(0);
}
return fp;
}
void read_lines(FILE* fp, char*** lines, int* num_lines) {
*num_lines = 0;
do {
*num_lines += 1;
*lines = malloc(*num_lines * sizeof(*lines));
for(int i = 0; i < *num_lines; ++i) {
*lines[i] = allocate_mem(fp, *lines[i]);
}
read_one_line(fp, *lines[*num_lines]);
} while(read_one_line(fp, *lines[*num_lines]) != NULL);
}
char* read_one_line(FILE* fp, char* line) {
fgets(line, sizeof(line), fp);
return line;
}
char* allocate_mem(FILE* fp, char* line) {
fseek(fp, 0, SEEK_END);
int length = ftell(fp);
fseek(fp, 0, SEEK_SET);
line = malloc((length + 1) * sizeof(char));
return line;
}
int main(int argc, char* argv[]){
char** lines = NULL;
int num_lines = 0;
FILE* fp = validate_input(argc, argv);
read_lines(fp, &lines, &num_lines);
print_lines(lines, num_lines);
free_lines(lines, num_lines);
fclose(fp);
return 0;
}
我们将不胜感激!
推荐答案
在函数 read_one_line
中, sizeof(line)
不正确, line
是一个指针,您不会获得容器 line
的大小,但是指针本身的大小(可能为8个字节),则需要传递容器的实际大小作为函数的参数,并在 fgets
中使用它.
In the function read_one_line
, sizeof(line)
is not right, line
is a pointer, you won't get the size of the container line
, but the size of the pointer itself (likely 8 bytes), you'll need to pass the actual size of the container as a parameter of the function and use that in fgets
.
这篇关于从文件中读取行并将它们存储在数组中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!