skip to Main Content

I want to redirect stdin to a file, so that I can write to the file and my program prints the character.
Below is a simple c code snippet, which prints stdin.

The programm is compiled with gcc and runs on debian 4.19.0 in virtualbox

//printchar.c

#include <stdio.h>
#include <stdlib.h>

int main(void) {
    
    int c;
    
    while( (c = getchar()) !='.') {
        putchar(c); 
    }

    return EXIT_SUCCESS;
}

I call the programm with ./printchar 0 < testfile.txt

Then i echo efghi > testfile.txt but nothing happens.
If i prefill the file with abcd, abcd is printed instantly after programm start, but again I can’t echo something to the testfile.

Isn’t it possible to redirect stdin in this way?

2

Answers


  1. I think you can do it using getcharlike this:

    int main(void) 
    {
        int c;
    
        while(1)
        {
          c = getchar();
          if (c == '.') break;
          if (c != EOF)
          {
            putchar(c);
          }
          else
          {
            usleep(100);
          }
        }
    
        return 0;
    }
    

    or using read like this:

    #include <stdio.h>
    #include <unistd.h>
    
    int main()
    {
      char c;
      int n;
      while(1)
      {
        n = read(0, &c, 1);
        if(n > 0)
        {
          if (c == '.') break;
          putchar(c);
        }
        else
        {
            usleep(100);
        }
      }
    
      return 0;
    }
    

    However, you need to append to the file using >> like:

    touch testfile.txt           // create empty file
    ./printchar < testfile.txt   // start program
    echo hello >> testfile.txt   // append to file
    echo world >> testfile.txt   // append to file
    echo . >> testfile.txt       // append to file
    
    Login or Signup to reply.
  2. You can also use heredoc << associated with redirection into a file like this :

        << keyCodeToStopWriting >> myFile
        first line
        second line
        keyCodeToStopWriting  //Stop the writing
    

    In this exemple I use >> to add line at the end of the file but you can overwrite it with >

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search