getline逐行,然后将整行存储在C中的一个数组中 [英] getline line by line and then store entire lines in an array in C
问题描述
这可能吗?或者是getline的限制..?
$ $ $ $ $ $ b $ $ ;
char * line;
ssize_t读取;
size_t bufsize = 32;
int i = 0;
char **数组;
array = malloc(bufsize * sizeof(char));
line = malloc(bufsize * sizeof(char));
fp = fopen(testing.txt,r); ((getline(& line,& bufsize,fp))!= -1){
printf(%s,line);
。
array [i] = line;
i ++;
}
fclose(fp);
printf(%s,array [0]);
返回0;
你需要为指针分配空间,而不是字符:
char ** array;
array = malloc(bufsize * sizeof(char *));
还需要为单独的行分配空间,并将行复制到它:
$ ((getline(& line,& bufsize,fp))!= -1){printf(%s ,线);
array [i] = malloc(strlen(line)+ 1);
strcpy(array [i],line);
i ++;
你的代码中的一个错误是所有的数组[ i] 指向变量
行
中的同一个字符串,由 getline()
每一个循环。
阅读函数getline 。它允许自行分配字符串,但不要忘记使用free()。
array [0] = NULL; ((getline(& array [i],& bufsize,fp))!= -1){
printf(%s,array [i]);
array [i + 1] = NULL;
i ++;
}
I'm trying to store every line separately in an array of strings. It doesn't work the way I've written it obviously all I'm getting when I try to print array[0] is the last line of the textfile. But when I print the variable "line" inside of the while loop I can print every single line in the text file but I can only seem to store the last line of the txt file.
Is this possible to do? Or is this a limitation of getline..?
int main()
{
FILE * fp;
char *line;
ssize_t read;
size_t bufsize = 32;
int i=0;
char **array;
array = malloc(bufsize * sizeof(char));
line = malloc(bufsize * sizeof(char));
fp = fopen("testing.txt", "r");
while ((getline(&line, &bufsize, fp)) != -1) {
printf("%s", line);
array[i] = line;
i++;
}
fclose(fp);
printf("%s", array[0]);
return 0;
}
As already has been mentioned, you need to allocate space for pointers, not chars:
char **array;
array = malloc(bufsize * sizeof(char*));
Also you need to allocate space for separate lines, and copy lines to it:
while ((getline(&line, &bufsize, fp)) != -1) {
printf("%s", line);
array[i] = malloc(strlen(line) + 1);
strcpy(array[i], line);
i++;
}
A mistake in your code is that all array[i]
points to the same string in variable line
, which is refilled by getline()
every loop cycle.
It may be useful to read manual about getline. It permits allocation of strings by itself, but don't forget to use free().
array[0] = NULL;
while ((getline(&array[i], &bufsize, fp)) != -1) {
printf("%s", array[i]);
array[i + 1] = NULL;
i++;
}
这篇关于getline逐行,然后将整行存储在C中的一个数组中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!