Reputation: 75
I have a text document looking like this:
#Something
info1
#Something
info2
#Something
info3
Now I want to read this file and skip all lines starting with #
and store the normal strings in a char
array.
I tried this:
void ReadFromFile()
{
char *info1;
char *info2;
char *info3;
char str[200];
int line1;
FILE *fp;
fp = fopen("game:\\Config.txt", "r");
if(!fp)
return;
while(fgets(str,sizeof(str),fp) != NULL)
{
line1++;
int len = strlen(str)-1;
if(str[len] == '\n')
str[len] = 0;
printf("%i", line1);
if(line1 == 2)
{
printf("%s", str);
info1 = str;
}
if(line1 == 4)
{
printf("%s", str);
info2 = str;
}
if(line1 == 6)
{
printf("%s", str);
info3 = str;
}
printf("\n");
}
fclose(fp);
printf("\n");
printf("%s\n", info1);
printf("%s\n", info2);
printf("%s\n", info3);
}
When I run this I get the output:
1
2info1
3
4info2
5
6info3
info3
info3
info3
Any idea why this is not working? I want the output to be:
1
2info1
3
4info2
5
6info3
info1
info2
info3
Upvotes: 1
Views: 77
Reputation: 19627
All these pointers:
char *info1;
char *info2;
char *info3;
point to the same buffer (each write through these pointers will overwrite the previous contents):
char str[200];
You'll have to make three separate buffers:
char str1[200];
char str2[200];
char str3[200];
Or:
char str[3][200];
while(int i = 0; fgets(str[i], sizeof(*str), fp) != NULL; )
{
// increment i if line without # was read
}
Or print the lines immediately after reading them (only one buffer required).
Upvotes: 3