-1
#include <stdio.h>
int main ()
{
  FILE * pFile;
  char ch;
  pFile = fopen ("G:\\ IJLAL.txt","w+");
  while((ch = getchar())!=EOF)
    putc(ch,pFile);
  fclose(pFile);
  return 0;
}

can you specify the problem??? I am totally new to fopen function. and please help me with this thing

Ahmad
  • 21
  • 8

3 Answers3

2

The getchar() function returns an int value, not a char. By forcing it into a char variable, you are making it impossible to detect the EOF.

Just change char ch to int ch and it will work fine.*


  • Actually, you will probably still have problems with the file name. Are you sure it should contain a space? And are you aware that \\ is encoded as a single backslash character?
r3mainer
  • 23,981
  • 3
  • 51
  • 88
  • Not working. The **EOF** don't closes the run window. i just put $EOF$ at the end but it continuous waiting for me to enter more. – Ahmad Nov 04 '14 at 20:07
  • i have made static text files with that edting. Now i want to enter the data from keyboard. – Ahmad Nov 04 '14 at 20:09
  • @Ahmad You put $EOF$ at the end? I'm not even sure what you mean by that. On a command line terminal, the EOF is usually indicated by hitting Control-D. With a sensible filename, your code will compile and run without any problems. – r3mainer Nov 04 '14 at 20:10
  • 2
    Wait a minute; Control-C aborts the program altogether. If Control-D doesn't work, [try Control-Z instead](http://stackoverflow.com/q/16136400/1679849). – r3mainer Nov 04 '14 at 20:18
  • But the program do saves the texts that is entered first than Control-C....Control-D doesn't work – Ahmad Nov 04 '14 at 20:21
1

According to the C99 standard (7.19.1.3):

EOF which expands to an integer constant expression, with type int and a negative value, that is returned by several functions to indicate end-of-file, that is, no more input from a stream;

The point is that EOF is out of the range of unsigned char. I am sure this was done intentionally so that all 256 basic and extended ASCII characters can still be returned, and are distinct from EOF

Degustaf
  • 2,655
  • 2
  • 16
  • 27
0

You can try this.

1 - Check fopen() return values -> print errno value (perror)

#include <stdio.h>
#include <stdbool.h>

int main(void)
{
    int     c;
    bool    run;
    FILE    *fd;

    run = true;
    fd = fopen("/tmp/file.txt", "w+");
    if (fd == NULL)
    {
        perror("fopen");
        return (1);
    }
    while (run == true)
    {
        c = getchar(); // Press ctrl + D for exit
        run = (!feof(stdin) && !ferror(stdin));
        if (run == true)
            putc(c, fd);
    }
    fclose(fd);
}

And if you want you can see this link.

Quentin Perez
  • 2,833
  • 20
  • 22