• C

program to copy /dev/stdin to a file.

hello all,

I need to copy stdin to a file.
in shell, bash,korn script I can do the following

var=$RANDOM ## random number for the file
 "tee -a /tmp/file-collected-fom-stdin-${var}.txt"

I want to do this in C, please give me an example program.
many thanks,
Who is Participating?
Hi CobolGuy9, so you want to write something from stdin to a file? I'm sure if this is what you need, but try it out. Hope it helps.

#include <stdio.h>

enum { OK, FAILED };
void writeUserInput(FILE *f);

     int result = OK;
     FILE *fd;
     char filename[] = "yourFile.txt";
     if( (fd = fopen(filename, "w")) == NULL )
         printf("Error opening %s...\n", filename);
         result = FAILED;
     return result;

void writeUserInput(FILE *f)
     char str[80];
     int length = 80;
     fgets(str, length, stdin);

     if( str[ (length = strlen(str) - 1) ] == '\n' )
          str[length] = '\0';
         while(getchar() != '\n')
         ;   //discard input until newline, then write line to file
         fputs(str, f);
sunnycoder, I don't see how dup() might help.

dr_country is closer to the quesion, but 'binary' stdin will be broken.

CobolGuy9, if you want to copy stdin to somewhere,

read from file descriptor 0 (or STDIN_FILENO, defined in <unistd.h>)
write to somewhere
then write to stdout (STDOUT_FILENO constant)

Here is the simplest 'tee.c' program without error checking:

#include <unistd.h>
#include <fcntl.h>
#define DEFAULT_PATH "/dev/null"
main(int argc, char *argv[])
  char buf[512];
  int fd, cnt;
  if (argc>1) fd=open(argv[1], O_WRONLY|O_CREAT);
  while(cnt=read(STDIN_FILENO, buf, sizeof(buf)))
    write(fd, buf, cnt),
    write(STDOUT_FILENO, buf, cnt);
  return 0;
Improve Your Query Performance Tuning

In this FREE six-day email course, you'll learn from Janis Griffin, Database Performance Evangelist. She'll teach 12 steps that you can use to optimize your queries as much as possible and see measurable results in your work. Get started today!

CobolGuy9Author Commented:
thank you all,

need to incorporate tmpfile() because file needs not to be static and stdin length maybe 0-10kb
CobolGuy9, may be you can describe entire problem?
In very rare cases you need to create tmp files. Most unix progams may accept stdin as an input.
CobolGuy9, did you try running the program? It takes a variable length stdin, so you can type stuff and when you press 'enter' everything that was typed will be written to a temp file. Let me know if it works for you.
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.