Search code examples
cbuffercommand-line-argumentsfgets

How do I use a text file passed in as an argument from the command line in C?


I am having the hardest time trying to figure out how to use a text file that is passed in as a command line argument. I simply dont know to get the file text into my program to be used. My code looks something like this....

    char buffer[80];
    int i;
    int lineCount = 0;

    fgets(buffer, 80, stdin);  //get the first line

    while (buffer != NULL) {  
        // do some stuff
    }//end fgets while

This is for a homework assignment and I know my teacher is going to run the program with the following command:

    username@mylunixbox$ ./a.out <data1> output1

data1 is the text file I am trying to use.


Solution

  • int main(int argc, char **argv)
    {
        int rc = EXIT_SUCCESS;
        for (int i = 1; i < argc; i++)
        {
            FILE *fp = fopen(argv[i], "r");
            if (fp == 0)
            {
                fprintf(stderr, "%s: failed to open file %s for reading\n",
                        argv[0], argv[i]);
                rc = EXIT_FAILURE;
            }
            else
            {
                char line[4096];
                while (fgets(line, sizeof(line), fp) != 0)
                    ...do stuff with the line read from the file...
                fclose(fp);
            }
        }
        return rc;
    }