getline逐行,然后将整行存储在C中的一个数组中 [英] getline line by line and then store entire lines in an array in C

查看:149
本文介绍了getline逐行,然后将整行存储在C中的一个数组中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图将每一行分别存储在一个字符串数组中。它不工作的方式,我已经写得很明显,当我尝试打印数组[0]是文本文件的最后一行。但是当我在while循环中打印变量line时,我可以打印文本文件中的每一行,但我似乎只能保存txt文件的最后一行。

这可能吗?或者是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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆