I am getting an infinite loop (in while loop) with this function. I am new to working with files, so I feel like I am missing something…I can’t see what is wrong.
void cipher(FILE* password_ptr,int n)
{
if (password_ptr == NULL)
{
printf("Error:password_ptr points to null");
return;
}
while(!feof(password_ptr))
{
fseek(password_ptr, 0, SEEK_CUR); // don't move
int en=fgetc(password_ptr)+n;
fseek(password_ptr, -1, SEEK_CUR); // move backwards one character
if(fputc(en,password_ptr)!=en)
{
printf("Error:fputc didn't work");
}
fseek(password_ptr, 0, SEEK_CUR);
}
fclose(password_ptr);
};
Thanks!
A side effect of calling
fseek()is that the EOF indication on the file gets cleared:C99 7.19.9.2/5 The fseek function:
Note that your code also uses the common anti-pattern of a loop controlled by the
feof()function. That function will not returnEOFuntil after an I/O operation gets you to that point (sets the end-of-file indicator). In other words, even when you enter the loop, thefgetc()may fail due to being at the end of the file (that’s what will set the end-of-file indicator). But then a subsequent seek will clear that indicator. In the meantime, you’ll have operated on theEOFas if it were a normal, successful read.See:
You might want to try the following loop instead:
You also need to think about how you want this bit of code to handle a situation where
enis out of the range of anunsigned char. Sincefputc()converts the character to be written to anunsigned charbefore writing it to the stream, ifenis outside of that range the “fputc didn’t work” error will be displayed. This might happen, for example, if addingnto the character read byfgetc()is larger than 255.