Search code examples
cpipestdinargv

Reading command line arguments from stdin


So I want to allow myself to run ./program so that it allows input for piping a text file.

EX: ./program < sometext.txt

I know that I can't get the data using argv, but I've been trying to google how to get it from stdin, and I can't seem to find the right keywords to google to get some basic understanding of how to do this. I'm sure it's done using scanf, but I still have a hard time trying to understand it.

Any sort of insight would be helpful, I don't need the exact code, though if it's simple enough, that would be very helpful. Thanks!


Solution

  • Here's a simple example (with no error checking) that reads stdin into a dynamically allocated character array and then prints it back to stdout:

    #include <stdio.h>
    #include <stdlib.h>
    
    int main(void)
    {
        int bufferSize = 100;
        char *buffer = malloc(bufferSize);
        int length = 0;
        int c;
    
        while ((c = getchar()) != EOF)
        {
            if (length == bufferSize)
            {
                bufferSize *= 2;
                buffer = realloc(buffer, bufferSize);
            }
    
            buffer[length++] = c;
        }
    
        for (int j = 0; j < length; j++)
        {
            putchar(buffer[j]);
        }
    
        free(buffer);
        return 0;
    }
    

    Hopefully that will get you started.