Reputation: 15
What I want to do here is to read a text file containing phone numbers. For example:
01011112222
01027413565
01022223333
I want to store these phone numbers into an array for later use. Here below is my code:
#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;
}
The problem is that whenever fgets
is called, it returns the same reference of strTemp
.
So every time it goes through the loop, it changes all value to the recent value in phoneNums
array.
I tried to declare char strTemp[14]
inside the while
loop, but it didn't work.
At this point, what could I try to solve this issue?
Thanks.
Upvotes: 0
Views: 68
Reputation: 3870
Hope this will help you
#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;
}
Here the dynamic allocation of memory for char *phoneNums[14];
pnoneNums=(char **)malloc(14*n); // where n is the numbers of phone numbers
Upvotes: 0
Reputation: 1334
Do the below changes to get the exact result.
Change the strTemp variable to pointer variable.
char *strTemp;
Inside while allocate the dynamic memory for the variable.
strTemp=malloc(14);
phoneNums[i]=fgets(strTemp,14,fl);
If you do like this it will create a new memory for each time so the value is stored in the different location. So it can't overwrite in the same location.
Upvotes: 1