1

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);
    }
}
5
  • 2
    At the for loop, you are already at end of file. Add rewind(text) before it. Commented Jan 14, 2021 at 12:47
  • 1
    Use rewind(text) to make it work before for because it has reached EOF in while Commented Jan 14, 2021 at 12:48
  • I wish it was always that easy.. Thanks!! Commented Jan 14, 2021 at 12:51
  • 2
    Also please change char ch, source; to int ch, source;. Function fgetc() returns int. In fact almost every library function that deals with "characters" does not use char but int (unless it is an array as a C string). Commented Jan 14, 2021 at 12:51
  • You cannot just check against len. You still have to check if fgetc returns 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. Commented Jan 14, 2021 at 13:52

1 Answer 1

0

Adding rewind to reset the fgetc to the first position in the txt file does the trick.

rewind(text);

for (int i = 0; i < len; i++)
{
    source = fgetc(text);
    printf("%c", source);
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.