【问题标题】:Reading from file into array, line by line逐行从文件读入数组
【发布时间】:2015-10-30 21:53:26
【问题描述】:

我正在尝试从 C 中的文件中读取。我的代码如下。似乎可以将所有内容都读入数组,但是当我尝试打印它时,出现错误Segmentation fault (core dumped)

  FILE *fp;
   char * text[7][100];
   int i=0;

   fp = fopen("userList.txt", "r");

   //Read over file contents until either EOF is reached or maximum characters is read and store in character array
   while(fgets((*text)[i++],100,fp) != NULL) ;

   printf("%s", &text[0]);

   fclose(fp);

有人能指出正确的方向吗?

我曾尝试阅读和复制其他类似案例的解决方案,但它们对用户来说非常具体。

【问题讨论】:

  • 应该只是text[0],而不是&text[0]
  • --> char text[7][100];.. i < 7 && fgets(text[i++],100,fp).. printf("%s", text[0]);
  • 数组应该是char text[7][100]。您声明的是一个二维指针数组,而不是字符串数组。
  • 感谢两者,虽然二维数组是我在数组中单独存储单词的下一个目标,但我想我把事情搞混了。

标签: c file


【解决方案1】:

所以第一部分,你不需要 指针 指向char[][]

char text[7][100];

第 2 部分,只是像普通人一样尊重你的字符串数组,这里没什么特别的:

while(fgets((text)[i++],100,fp) != NULL) ;

现场示例:http://ideone.com/MADAAs

注意事项:

  1. 如果您的输入文件超过 7 行,您就会遇到问题。
  2. Why is “while ( !feof (file) )” always wrong?

【讨论】:

  • 谢谢,它解决了。我正在尝试制作的程序和文件都非常简单,所以我不担心最后两个警告,但是谢谢。
【解决方案2】:
char * text[7][100]; //wrong - this is 2 diminutions array of char pointers, replace it with 
char text[7][100];

while(fgets((*text)[i++],100,fp) != NULL) ; // replace this with
 while(fgets(&text[i++][0],100,fp) != NULL) ; 

注意:如果您需要在当前范围之外使用它,在堆上分配一些内存并使用堆的指针,此代码将在函数的当前范围内(在堆栈上)工作。

【讨论】:

  • @Ben 为什么不对? !我指向这个数组的 7 个字符串中每个字符串的第一个字符,text[0][0]text[1][0]text[2][0]text[3][0]text[4][0]text[5][0]text[6][0]
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2018-06-20
  • 2017-01-20
  • 2012-11-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多