c - 将文件读取到数组字符串

标签 c string file

我想知道如何正确读取文件并将每一行放入 C 中的数组字符串中。

我有一个文件,上面写着以下内容

one
two
three
four

我尝试写这样的东西:

int read_file(FILE *fp){
   char readLine[MAX_LEN];
   char *myarray[20];
   int counter =0;
   int i =0;
   while(fgets(readLine,MAX_LEN,fp) != NULL){
      myarray[counter] = readLine;
      counter++;
   }

   /*printing the array*/
   while(i<counter){
      printf("%d  %s",i,myarray[i]);
      i++;
   }
}

主要内容是这样的

int main(){
   FILE *fp;
   fp = fopen("my.txt","r");
   if(fp == NULL){
      fprintf(stderr,"File does not exist");
      return EXIT_FAILURE;
   }

   read_file(fp);
}

但是,在打印时我得到:

four
four
four
four

即使我使用 printf("%s",myarr[2]) 打印,我仍然得到 4

有人知道问题出在哪里吗?

最佳答案

当您覆盖用于接受输入的缓冲区时,您确实需要复制该行(通过 strdup()):

int read_file(FILE *fp){
   char readLine[MAX_LEN];
   char *myarray[20];     // Note char pointer!
   int i, counter = 0;
   while (counter < 20 && fgets(readLine,MAX_LEN,fp) != NULL) {    // Note limit!
      myarray[counter] = strdup(readLine);
      counter++;
   }

   /*printing the array*/
   for (i = 0; i < counter; i++)
      printf("%d  %s",i,myarray[i]);

   /* free the lines */
   for (i = 0; i < counter; i++)
        free(myarray[i]);   
}

关于c - 将文件读取到数组字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18356901/

相关文章:

c - R包开发: how to check whether the type of SEXP is "big.matrix"?

c++ - 'a' == 'b' 。这是个好办法吗?

c - 使用指针到指针的重新分配行为

c# - 有没有办法在调试中设置断点 "at this very moment"?它与任何编程语言或 IDE 有关

java - 如何检查和替换java中字符串中包含的特殊字符(\)?

file - 是否可以为 Zend 文件传输适配器设置名称、类型、大小?

c - 从文本文件中读取到 C 中的数组中的标记化

C++ 删除或覆盖文件中的现有信息

c# - 如何将一个文本文件拆分成多个文件?

c - 在 C 中使用 strcpy() 和复制 char* 的地址之间的区别