I am aware that in c there are functions getc() and ungetc().
I would need this counter-function for fgetc(), sadly unfgetc() doesn't really exist. So I tried writting it on my own.
This is how it looks:
int getNextChar(FILE* fd)
{
// get the character
int nextCharacter = fgetc(fd);
// fseek it back, so you don't really move the file descriptor
fseek(fd, -1, SEEK_CUR);
// returning the char (as int)
return nextCharacter;
}
But well... that doesn't seem to work.
I call it inside a while loop, like this.
while ( (c = fgetc(fd)) != EOF)
{
cx = getNextChar(fd);
printf("%c", c);
}
It gets stucked on the last character of the file (it prints it with every iteration to infinity). Now a little explanation why I need that in case that I'm doing it all wrong and that there would be another suitable solution.
I need to check the next character on being EOF. If it is EOF, I force send token, that is created in the while loop (this part is not important for my issue, so I didnt include it).
I am going through the loop and whenever I find a character that doesnt respond to a mask, I assume that I should send a token and start making a new one with that character that doesnt respond. Naturally, when I read the last char in the file, no next iteration will be done, therefore I won't send the last token. I need to check next char to be EOF. If it is EOF, I force send token.
Thank you for your advices!
Answer
You need to check that nextCharacter
isn't EOF
, since if it is, you'll still back off, thus causing the outer reading to never see the end of the file. Also check return values of more functions, like fseek()
.
No comments:
Post a Comment