Reputation: 423
I have this program in C and I'm trying to get strings from a file and put them in a array. It works perfectly for reading the file, but seems it messes up with the assign in the array.
int getUsers(){
char userVect[5][25];
char user[24];
int i = 0, j = 0, k;
FILE *usernames;
usernames = fopen("usernames.cfg", "r");
if (usernames == NULL){
perror("usernames - err");
return(-1);
}
while(!feof(usernames)){
fgets(user, sizeof(user), usernames);
strcpy(userVect[j], user);
j++;
}
fclose(usernames);
for(k=0; k<j; k++)
printf("Usernames are: %s\n", userVect[j]);
return 0;
}
It's surely from the user variable, or from the strcpy function, but not sure what. Thx.
Upvotes: 0
Views: 71
Reputation: 24157
Beside the trouble with feof
and the limit of 5 users not taken into account there are many other issues with the program shown as exemple:
fgets
won't correctly read lines if there are more than 24 characters (size of your username before). Lines of more than 24 characters will be treated as multiple usernames. Very unlikey what is intended. This should be taken into account, for instance explicitely truncating username after reading the end of line.
If the line is less than 24 characters the username will contain the \n
line terminator. Which is also unlikely to be intended. The line terminator should probably be striped as it is not part of the name. If a line is empty you'll get an empty name with a trailing '\n'.
In the final printing loop, you should access names in userVect using loop index k, not j as written, or you won't see much: only the next to last name repeated multiple times, which is uninitialised stack memory. It could be litterally anything.
Not much to fix, but it should fix what you see.
Upvotes: 0
Reputation: 206557
See Why is “while ( !feof (file) )” always wrong?.
Here's my suggestion to avoid the problems associated with using while (!feof(username))
.
fgets
return NULL if it is unable to read any data. The conditional of the while
loop can be modified to use that value.
while(fgets(user, sizeof(user), usernames) != NULL){
strcpy(userVect[j], user);
j++;
}
Rest of your code is OK as long as there are 5 or less lines in the input file. You can make it more robust by adding another check.
while( j < 5 && fgets(user, sizeof(user), usernames) != NULL ){
strcpy(userVect[j], user);
j++;
}
You need to also fix the printf
line to use k
instead of j
.
printf("Usernames are: %s\n", userVect[k]); // Use k, not j.
Upvotes: 1
Reputation: 223689
As mentioned in the comments, you shouldn't use feof
. Since fgets
will return NULL
on error or end-of-file, you can use that for your loop condition.
while(fgets(user, sizeof(user), usernames)) {
strcpy(userVect[j], user);
j++;
}
The other problem is here:
for(k=0; k<j; k++)
printf("Usernames are: %s\n", userVect[j]);
Your loop variable is k
, but you're using j
instead. That's why you're seeing garbage output.
for(k=0; k<j; k++)
printf("Usernames are: %s\n", userVect[k]);
Upvotes: 1