Reputation: 193
I'm having some trouble with my code. I'm trying to read in some previous commands saved to a file, and place them in my array to use for later.
Here is my relevant piece of code:
if( (pastHist = fopen("history.txt", "r+")) == NULL)
{
pastHist = fopen("history.txt", "w+");
}
else
{
printf("%s", "INSIDE the else!");
pastHist = fopen("history.txt", "r+");
fscanf(pastHist, "%s", fstring);
while (fstring != NULL)
{
printf("%s %s", "the read in string is: ", fstring);
strcpy(cmndLine[cmndIndex], fstring);
strcpy(cmndLinecpy[cmndIndex], fstring);
cmndIndex++;
cmndNum++;
fscanf(pastHist, "%s", fstring);
}
}
Now the code writes to the file fine. (the writing part is held elsewhere). If I read from a file I wrote to before and the file said:
ls rmdir angel history
then i use this print statement to double check what i'm reading... it prints out "INSIDE the else! the read in string is: lsthe read in string is: rmdirthe read in string is: angelthe read in string is: historythe read in string is: historythe read in string is: history
... and it repeats that the last thing read in was history a million times. Why is this the case? I also tried with the while condition
while(getchar() != EOF)
but that gave me the same thing.
please help. Thanks.
Upvotes: 0
Views: 64
Reputation: 225032
fstring
can never be set to NULL by that call to fscanf
. What you want to check is the return value of fscanf
.
Your getchar()
loop likewise does nothing useful - it's reading from the standard input, not from your file.
Upvotes: 1