逐行读取文件并将其存储到数组中不起作用

时间:2014-07-24 07:42:06

标签: c fgets arrays

我想在这里做的是阅读包含电话号码的文本文件。例如:

01011112222
01027413565
01022223333

我想将这些电话号码存储到一个数组中供以后使用。以下是我的代码:

#include <stdio.h>
#include <stdlib.h>
int main(){
   FILE *fl = NULL;
   char* phoneNums[10];

   int i = 0;
   fl = fopen("phoneNum.txt", "r");

   if(fl != NULL){
      char strTemp[14];

      while( !feof(fl) ){
        phoneNums[i] = fgets(strTemp, sizeof(strTemp), fl); 
        i++;
      }
      fclose(fl);
   }
   else{
      printf("File does not exist");
   }

   return 0;
}

问题在于,只要调用fgets,它就会返回strTemp的相同引用。

因此,每次循环时,它都会将所有值更改为phoneNums数组中的最新值。

我尝试在char strTemp[14]循环中声明while,但它不起作用。

此时,我可以尝试解决这个问题吗?

感谢。

2 个答案:

答案 0 :(得分:1)

进行以下更改以获得准确的结果。

将strTemp变量更改为指针变量。

 char *strTemp;

在为变量分配动态内存时。

 strTemp=malloc(14);
 phoneNums[i]=fgets(strTemp,14,fl);

如果您喜欢这样,它将每次创建一个新内存,以便将值存储在不同的位置。因此它无法在同一位置覆盖。

答案 1 :(得分:0)

希望这会对你有所帮助

#include <stdio.h>
#include<string.h>
#include <stdlib.h>
int main(){
    FILE *fl = NULL;
    char    phoneNums[3][14]; // you didn't allocate memory here. i am using static memory(for 3 phone numbers)
    int i = 0,j;
    fl = fopen("phoneNum.txt", "r");

    if(fl != NULL){
            char strTemp[14];

            while( fgets(strTemp, sizeof(strTemp), fl) ){
                    strcpy(phoneNums[i],strTemp); // you need to string copy function to copy one string to another string
                    i++;
            }
            fclose(fl);
    }
    else{
            printf("File does not exist");
    }
    for(j=0;j<i;j++) // i am printing the array content
            printf("%s\n",phoneNums[j]);

    return 0;
}

这里是char *phoneNums[14];

的内存动态分配
pnoneNums=(char **)malloc(14*n); // where n is the numbers of phone numbers
相关问题