What is wrong with this code of file handling in c?

101 views Asked by At

I am trying to write content in a file from terminal. File is creating but content is not written into the file.

    #include<stdio.h>
    #include<stdlib.h>
    #include<math.h>
    int main(int argc, char *argv[])
    {
        FILE *fp;
        fp=fopen(argv[1],"w");
        char ch;
        while((ch=getchar())!=EOF)
        {
           putc(ch,fp);
        }
        fclose(fp);
        return 0;
    }
2

There are 2 answers

0
gsamaras On BEST ANSWER

If you don't signal EOF (Ctrl+Z in Windows and Ctrl+D in Linux), then the loop will continue to execute until it receives that signal.

If you attempt to read the file with your own eyes while the program is still on execution, then the file stream will not have close (fclose(fp); will not have execute), thus the file will appear to you empty, even though the content will be shown to you, when the file stream closes.

0
Matteo Tosato On

The following works fine:

#include<stdio.h>
#include<stdlib.h>
#include<math.h>
int main(int argc, char *argv[])
{
    FILE *fp;
    fp=fopen(argv[1],"w");
    char ch;
    while(1)
    {
        ch = (char)getchar();
        putc(ch,fp);
        if(ch == '.') break;
    }
    fclose(fp);
    return 0;
}