Kavish  Dwivedi
Kavish Dwivedi

Reputation: 745

Why is the input not being written to file even if fprintf is used to pass the input to the file pointer?

I was trying some questions based on C and got stuck in this particular problem . Here according to me , old.out file should be written with whatever we take input with scanf as fprintf assigns the input to the file pointer but to my surprise, I saw that nothing is being written to old.out as the later while loop isn't executed . How is this happening ? Has it to do with my misunderstanding of fprintf function ? I have pasted the code below .

#include<stdio.h>
main()
{
    FILE *fp;
    char a;
    fp=fopen("old.out","w");
    if(fp==0)
        printf("File opening error");
    else
    {
        for(scanf("%c",&a);a!=EOF;scanf("%c",&a))
            fprintf(fp,"%c",a);
        fclose(fp);
        fp=fopen("old.out","r");
        while(!feof(fp))
            putchar(getc(fp));
    }
    return 0;
}

Upvotes: 0

Views: 205

Answers (2)

user529758
user529758

Reputation:

scanf() doesn't set its argument to EOF when it has no more characters to read. So your for loop is an infinite loop. Two things to change:

  1. Instead of making assumptions, read the documentation.

  2. Use fgets() instead of scanf(). (Forget scanf(), after all, it doesn't do what you think it does, there are a lot of much better and friendly functions out there, especially for a beginner.)


"Okay, okay, but I can haz the codez?"

You can:

#include <stdio.h>
#include <limits.h>
#include <assert.h>

int main()
{
    char buf[LINE_MAX];
    fgets(buf, sizeof(buf), stdin);

    FILE *fp = fopen("old.out", "w");
    assert(fp);
    fputs(buf, fp);
    fclose(fp);

    fp = fopen("old.out", "r");
    assert(fp);
    if (fgets(buf, sizeof(buf), fp))
        puts(buf);
    fclose(fp); 

    return 0;
}

Upvotes: 6

unwind
unwind

Reputation: 399871

There's quite a lot of problems.

For one, scanf() won't assign EOF, it will *return * EOF. Also, EOF does not fit in a char (it's an int value), so a != EOF is dangerous. Also, checking feof() before doing I/O is not a good idea.

Upvotes: 3

Related Questions