I'm trying to get the fgetc command working in a very simple for loop. While (pun intended) it works in a while loop it doesn't work in a for loop and I can't figure why.
It should just grab whatever is in the txt file and print it out encrypted with the increment of len. To compare the original, I created a for loop which runs len times to get fgetc again and print out the original message.
The loop runs through but I can't figure why it doesn't pick up the fgetc value into char source.
#include <stdio.h>
int len;
char ch;
char source;
int main(void)
{
FILE* text = fopen("welt.txt", "r");
while((ch = fgetc(text)) != EOF)
{
printf("%c", ch + len);
len++;
}
printf("\n%i\n", len);
for (int i = 0; i < len; i++)
{
source = fgetc(text);
printf("%c", source);
}
}
forloop, you are already at end of file. Addrewind(text)before it.rewind(text)to make it work beforeforbecause it has reached EOF inwhilechar ch, source;toint ch, source;. Functionfgetc()returnsint. In fact almost every library function that deals with "characters" does not usecharbutint(unless it is an array as a C string).len. You still have to check iffgetcreturns EOF, as there is no guarantee against read errors or that the file does not change. Indeed, you haven't even checked if the first loop terminated because it reached the end of the stream or if there was a read error.