Thread: reading and writing to stdin, stdout and file

  1. #1
    Registered User
    Join Date
    Apr 2016
    Posts
    10

    Post reading and writing to stdin, stdout and file

    I want to read a string from stdin and write it to stdout and in a file. Reading/Writing from standard input/output works fine. File is empty.

    Note: Ctrl-Z is the eof for stdin.

    What's wrong with this code?

    Code:
        fp=fopen("par3.txt","w");
        while(1)
        {
            fflush(stdin);
            fgets(line,40,stdin);
            if(feof(stdin))break;
            fputs(line,fp);
            fputs(line,stdout);
            fputc('\n',stdout);
        }
        fclose(fp);

  2. #2
    Registered User
    Join Date
    Jun 2015
    Posts
    1,643
    You should post a small, complete, runnable program so we can run it.

    You should test if fp is NULL after attempting to open the file to see if it failed.

    You shouldn't use fflush(stdin) as it is "undefined behaviour" in Standard C (although it may do what you want on a particular system). You don't seem to have any need for it in your code.

    It is best to test the return value of fgets for NULL to indicate the end-of-file condition (or an error condition) instead of using feof.

    Ctrl-Z is not the "eof" for stdin. It is a keyboard signal to send the eof signal to the program. It's also just for Windows. It is Ctrl-D on unix.

    This is how your code would normally be written:
    Code:
    FILE *fp = fopen("par3.txt", "w");
    if (fp == NULL) {
        perror("fopen");
        exit(EXIT_FAILURE);  // EXIT_FAILURE is defined in stdlib.h
    }
    while (fgets(line, 40, stdin) != NULL) {
        fputs(line, fp);
        fputs(line, stdout);
        fputc('\n', stdout); // this adds an extra newline
    }
    fclose(fp);
    Overall I can't see anything that would stop the output file from having the data.
    Last edited by algorism; 05-24-2016 at 02:21 PM.

  3. #3
    Registered User
    Join Date
    Apr 2016
    Posts
    10
    Precious help! Thank you algorism. Good lesson

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Stdin stdout
    By mark707 in forum C Programming
    Replies: 3
    Last Post: 09-16-2013, 10:38 AM
  2. Recreating stdout/stdin
    By Zarniwoop in forum C Programming
    Replies: 1
    Last Post: 10-02-2008, 06:22 PM
  3. writing stdout to a file
    By SIKCAR in forum C Programming
    Replies: 4
    Last Post: 09-09-2002, 06:35 AM
  4. STDIN stdout
    By GreyMattr in forum Linux Programming
    Replies: 2
    Last Post: 08-01-2002, 01:29 PM
  5. stdin/stdout
    By lmmds2 in forum C Programming
    Replies: 2
    Last Post: 12-10-2001, 02:07 PM

Tags for this Thread