Hi,
I was working on something when I noticed that the following code produced a duplicate char before reaching at the end of the file if it had a blank line (with no chars at the file) before the end of the file and without it, it would run file.
-
int ReadFromFile(int argc, char **argv)
-
{
-
// our file pointer, initialized at NULL
-
FILE *fStream = NULL;
-
-
char buf[10];
-
char p;
-
int i = 0;
-
-
if( (fStream = fopen(argv[1], "r")) == NULL )
-
{
-
// error, return the function
-
return FALSE;
-
}
-
-
while( !feof( fStream ) )
-
{
-
fscanf(fStream, "%c", &p);
-
-
-
if(p != '\n')
-
{
-
buf[i] = p;
-
i++;
-
}else {
-
buf[i] = '\0';
-
i = 0;
-
}
-
-
printf("%c", p);
-
-
}
-
-
-
return TRUE;
-
}
-
The input file has the following lines
lol
asdf
mmd
(here was the blank line)
the output was:
lol
asdf
mmdd
if the blank line was present, when it didn't have that line the output was
lol
asdf
mmd
Why does this happen I have an idea but I've tried to make a workaround and came at a dead end... Any help?
Update: found a workaround but still I can't explain to myself why the above code fails to provide the output I like... The workaround is the following code
-
int ReadFromFile(int argc, char **argv)
-
{
-
// our file pointer, initialized at NULL
-
FILE *fStream = NULL;
-
-
char strBuf[20];
-
char intBuf[10];
-
char p;
-
int i = 0, j = 0;
-
-
if( (fStream = fopen(argv[1], "r")) == NULL )
-
{
-
// error, return the function
-
return FALSE;
-
}
-
-
do
-
{
-
p = fgetc(fStream);
-
-
strBuf[i] = p;
-
i++;
-
-
if(p == '\n' || p == EOF)
-
{
-
strBuf[i-1] = '\0';
-
i = 0;
-
}
-
-
}while( !feof(fStream) );
-
-
-
-
return TRUE;
-
}
-
I am sure the problem lies with fscanf but I can't figure why this is happening...