Search code examples
cioio-redirection

Save input from one program


I have a program idea which is comprised of two parts:

  1. I would like to keep track of the input to one program and save the input to a file
  2. Then feed the saved input back into the program later. (I have this accomplished)

Simple input program: testProgram.c

  1 #include <stdio.h>
  2 int main() {
  3   char str[100];
  4   int i;
  5 
  6   printf("Enter a value : ");
  7   scanf("%s %d", str, &i);
  8 
  9   printf("\nYou entered: %s %d\n", str, i);
 10   
 11   return 0;
 12 }                           

How would I save the input from one program to a file (or program)?

EDIT Sorry my question is very unclear. I see now how it could be perceived in different ways. I should have been more clear with what I was asking.

David's summary of my question: "How do I take user input and then write the questions and the answer to a file at the beginning of my program that I can later then read back into my program from the file?"" is true, except I don't care to keep the questions, just the answers (i.e., the input). I also would like it general purpose and to not alter the program I want to receive the input from. This means I can grab the input a user enters into any program, without changing any code.

Ideal behavior If I ran the above program with input hello and 1, the terminal should produce:

Enter a value : hello 
1

You entered: hello 1

These inputs should be recorded in an outputFile of the input (confusing, I know) to the previous program. This file would look like:

hello
3

Solution

  • From what I get from your comments, the question you are asking is "How do I take user input and then write the questions and the answer to a file at the beginning of my program that I can later then read back into my program from the file?"

    Despite the obvious that you should maintain the data in memory in a usable form to avoid the file I/O, there is learning to be had in how to use a file in this way. You have a couple of options, you can either open the file in "rw" (read/write) mode and use rewind(), lseek() or fgetpos()/fsetpos() to move the file position indicator around as needed, a more basic way is simply to open the file in "w" write mode for writing, write what you need to the file, fclose() the file and then open the file in "r" read mode and read the data back in.

    Let's look at the basic case and see if that is what you are looking for. To open a file for writing you simply provide a filename to fopen() and then validate that your file was in fact open and is ready for use, e.g. using the filename provided in the first argument to the program, you could do:

    #include <stdio.h>
    #include <string.h>
    
    #define MAXC 1024   /* if you need a constant, #define one (or more) */
    
    int main (int argc, char **argv) {
    
        char buf[MAXC], pet[MAXC];  /* read buffer, and buffer to store pet */
        FILE *fp = NULL;            /* FILE* pointer to hold open file stream */
    
        if (argc < 2) { /* validate at least 1 argument given */
            fprintf (stderr, "usage: %s outfilename\n", argv[0]);
            return 1;
        }
    
        /* validate file open for writing */
        if ((fp = fopen (argv[1], "w")) == NULL) {
            perror ("file open for write failed");
            return 1;
        }
    

    Next you will prompt the user for whatever information your want and then read his response into buf using fgets() (don't forget all line-oriented input function read and store the '\n' in the buffer they fill), e.g.

        fputs ("type of pet?: ", stdout);   /* prompt user */
        if (!fgets (buf, MAXC, stdin)) {    /* read/validate input */
            fputs ("(user canceled input)\n", stderr);
            return 1;
        }
        buf[strcspn(buf, "\n")] = 0;        /* trim trailing '\n' from buf */
        strcpy (pet, buf);                  /* copy pet from buf to pet */
    

    Now you have read the user input, and trimmed the trailing '\n' using strcspn(), you are ready to write your first question and answer to the file, e.g.

        fprintf (fp, "type of pet?: %s\n", pet);    /* write Q & A to file */
    

    Repeat the prompt, read, trim and output to file for as many inputs as you have, e.g.

        /* prompt user with 2nd question */
        fprintf (stdout, "your %s (\"has fleas\"/\"has no fleas\")? ", pet);
        if (!fgets (buf, MAXC, stdin)) {    /* read/validate input */
            fputs ("(user canceled input)\n", stderr);
            return 1;
        }
        buf[strcspn(buf, "\n")] = 0;        /* trim trailing '\n' from buf */
    
        fprintf (fp, "your %s %s\n", pet, buf);     /* write Q & A to file */
    

    Now close the file you have been writing to:

        if (fclose (fp))    /* always validate close after writing to file */
            perror ("fclose");
    

    Next, open the file for reading and read all lines of data stored in the file and output the lines to stdout so you can confirm what you have written:

        if ((fp = fopen (argv[1], "r")) == NULL) {  /* open/validate for reading */
            perror ("file open for read failed");
            return 1;
        }
    
        fputs ("\ndata written to file:\n\n", stdout);  /* write heading */
        while (fgets (buf, MAXC, fp))   /* read/validate each line from file */
            fputs (buf, stdout);        /* print it to stdout */
    
        fclose (fp);    /* simply close file after reading */
    
        return 0;
    }
    

    That's the basic approach. Compile it and give it a try:

    Example Use/Output

    $ ./bin/rdstdin_wrtfile dat/petfile.txt
    type of pet?: dog
    your dog ("has fleas"/"has no fleas")? has fleas
    
    data written to file:
    
    type of pet?: dog
    your dog has fleas
    

    Check the file contents itself from the shell:

    $ cat dat/petfile.txt
    type of pet?: dog
    your dog has fleas
    

    So there is not much to it, but the key is to validate every input and output by checking the return. That is the only way you can have any confidence that your operation completed successfully. Let me know if this was what you were asking or if I missed the intent of your question. I'm happy to help further.