Question

I'm trying to recreate a program I saw in class. The teacher made a file with 10 lines, he showed us that the file was indeed created, and then he displayed its contents. My code doesn't work for some reason, it just prints what looks like a"=" a million times and then exits.

My code:

void main()
{
    FILE* f1;
    char c;
    int i;
    f1=fopen("Essay 4.txt","w");
    for(i=0;i<10;i++)
        fprintf(f1," This essay deserves a 100!\n");
    do
    {
        c=getc(f1);
        putchar(c);
    }while(c!=EOF);
}

What is the problem? as far as I can see I did exactly what was in the example given.

Was it helpful?

Solution

The flow is as such:

  • You create a file (reset it to an empty file if it exists). That's what the "w" mode does.
  • Then you write stuff. Note that the file position is always considered to be at the very end, as writing moves the file position.
  • Now you try to read from the end. The very first thing you read would be an EOF already. Indeed, when I try your program on my Mac, I just get a single strange character just as one would expect from the fact that you're using a do { } while. I suggest you instead do something like: for (c = getc(f1); c != EOF; c = getc(f1)) { putchar(c) } or similar loop.
  • But also, your reading should fail anyway because the file mode is "w" (write only) instead of "w+".

So you need to do two things:

  • Use file mode "w+".
  • Reset the file position to the beginning of the file after writing to it: fseek(f1, 0, SEEK_SET);.
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top