0

I have the following code:

#include <stdio.h>

int main()
{
   char c = 0;
   fclose(stdin);
   stdin = fopen("newin", "r");
   if(stdin != NULLL)
   {
      scanf("%c", &c);
      printf("%d", c);
   }
   else
       printf("Error");
}

I want my program to wait for a change in the stdin file. I created it blank, but it returns 0.

If a put like a 'a' char in it it prints 97 like it should.

How can I make the scanf wait for a change in the file, like it was waiting for me to write in the terminal window?

Sean Bright
  • 118,630
  • 17
  • 138
  • 146

1 Answers1

1

How can I make the scanf wait for a change in the file, like it was waiting for me to write in the terminal window?

You can't.

Input from stdin and a file from disk are handled differently. When you are reading from a file, the file must have everything in order before you open it to read from it.

R Sahu
  • 204,454
  • 14
  • 159
  • 270
  • Is there any way to simulate that? Like I want to have a process running and another one giving inputs to it. – user7122079 Jan 06 '17 at 18:56
  • Sure. You can fork a child process and use pipes between them. See http://stackoverflow.com/questions/4812891/fork-and-pipes-in-c. – R Sahu Jan 06 '17 at 18:58
  • If you put your program in a loop reading the file and make it acts when it founds a signal, and you're able to write in your archive. – Gabriel Pellegrino Jan 06 '17 at 19:03
  • I don't understand why using pipes is no a general solution. – R Sahu Jan 06 '17 at 19:04
  • 1
    Because you have to create a parent and a child process, I just want to create a process and then send and receive information from it, by another processes, that can be running or not... – user7122079 Jan 06 '17 at 19:11
  • I also would like to use it when a scanf is called not a read or a write... – user7122079 Jan 06 '17 at 19:14
  • You just experienced [the XY problem](http://meta.stackexchange.com/questions/66377/what-is-the-xy-problem). I suggest creating a new post where you state the actual problem you want to solve, what you have tried to solve it, and what obstacles you ran into. – R Sahu Jan 06 '17 at 19:36