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?

3
  • Why are you closing stdin? You might want to check out this answer: stackoverflow.com/a/5925575/1212725. You might also want to check the return code from fclose. Commented Jan 6, 2017 at 18:38
  • You want to write in your file and then your program read what you have writed? Kind of like you did in terminal? Commented Jan 6, 2017 at 18:45
  • @GabrielPellegrino yes, that is my idea Commented Jan 6, 2017 at 18:55

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

7 Comments

Is there any way to simulate that? Like I want to have a process running and another one giving inputs to it.
Sure. You can fork a child process and use pipes between them. See stackoverflow.com/questions/4812891/fork-and-pipes-in-c.
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.
I don't understand why using pipes is no a general solution.
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...
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.