C How to take multiple files for arguments?

2019-08-10 12:42发布

How would you ask for the user to input files as arguments to be used (as many as they would like)? Also How would you print to a file?

scanf("%s", user_filename);

    FILE *fp;
    fp = fopen (user_filename, "r");

I have tried doing various things to it but I can only get it to take one file.

1条回答
狗以群分
2楼-- · 2019-08-10 13:03

The easiest way to pass some file names to your C program is to pass them as arguments to your C program.

Arguments are passed to a C program using the parameters to main:

int main( int argc, char *argv[] )
{
    ...
}

The value argc indicates how many parameters there are, and argv[] is an array of string pointers containing the arguments. Note that the first argument at index 0 (the string pointed to by argv[0]) is the command name itself. The rest of the arguments passed to the command are in argv[1], argv[2], and so on.

If you compile your program and call it like this:

my_prog foo.txt bar.txt bah.txt

Then the value of argc will be 4 (remember it includes the command) and the argv values will be:

argv[0] points to "my_prog"
argv[1] points to "foo.txt"
argv[2] points to "bar.txt"
argv[3] points to "bah.txt"

In your program then, you only need to check argc for how many parameters there are. If argv > 1, then you have at least one parameter starting at argv[1]:

int main( int argc, char *argv[] )
{
    int i;
    FILE *fp;

    // If there are no command line parameters, complain and exit
    //
    if ( argc < 2 )
    {
        fprintf( stderr, "Usage: %s some_file_names\n", argv[0] );
        return 1;  // This exits the program, but you might choose to continue processing
                   // the other files.
    }

    for ( i = 1; i < argc; i++ )
    {
        if ( (fp = fopen(argv[i], "r")) == NULL )
        {
            fprintf( stderr, "%s: Gah! I could not open file named %s!\n", argv[0], argv[i] );
            return 2;
        }

        // Do some stuff with file named argv[i], file pointer fp

        ...
        fclose( fp );
    }

    return 0;
}

This is just one of several different ways to do it (functionally and stylistically), depending upon how you need to process the files.

查看更多
登录 后发表回答