0

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.

Oria Gruber
  • 1,513
  • 2
  • 22
  • 44
  • I suppose you want 'rw' mode. – maverik May 13 '13 at 18:02
  • It's not only that, I think it also has to do with me not advancing f1. c=getc(f1) gets the first char, putchar(c) prints it, but when i do it again ,it will still just print the first char...right? – Oria Gruber May 13 '13 at 18:03
  • Nope, 'getc' will move the read cursor. Another issue that you possibly need to do seek: fseek(f1, 0, SEEK_SET); before reading. – maverik May 13 '13 at 18:05

1 Answers1

0

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);.
DarkDust
  • 90,870
  • 19
  • 190
  • 224