laker001
laker001

Reputation: 417

Reading from argv in C

I want to read the path of three files (for example, "../c/..file"), and a long from argv[] and bind them to three already created char* 's, and also a long value called num.

Here's my main function:

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

    char* file1 = NULL;
    char* file2 = NULL;
    char* file3 = NULL;
    long num = 0;

    //copy the file paths to the char*'s
    strcpy(file1, argv[1]);
    strcpy(file2, argv[2]);
    strcpy(file3, argv[3]);
    // convert from string to long int
    num = strtol(argv[4],NULL,0);

}

However this does not work, and the filename of the files and the value of the long, don't end up on the variables, as they're supposed to.

How can i fix this ?

In my program i check the argc values to make sure i'm not passing wrong stuff, but here i wrote the function this way just to illustrate my problem.

Upvotes: 2

Views: 2657

Answers (3)

jschultz410
jschultz410

Reputation: 2899

Don't strcpy into pointers that aren't pointing at allocated memory. Instead, just set them equal to the pointers in the argv array, which already do point at allocated memory. Like so:

int main(int argc, char *argv[])
{
    if (argc < 5)
        fprintf(stderr, "usage: %s <file1> <file2> <file3> <num>\n", argv[0]), exit(1);

    char *file1 = argv[1];
    char *file2 = argv[2];
    char *file3 = argv[3];
    long  num   = strtol(argv[4], NULL, 0);

    /* Do stuff */

    return 0;
}

Upvotes: 8

Bhuvanesh
Bhuvanesh

Reputation: 1279

some times we missed some of the argument, for that we need check whether all the arguments are given or not.

  main(int argc,char *argv[])
  {
         if(argc != 5)
            printf("Error message");
         else{
             //perofmr your operation what you want
             }
  }

Upvotes: 2

Vlad from Moscow
Vlad from Moscow

Reputation: 310980

If you want to copy strings from argv then you have to allocate memory for these strings in the program. For example

int main(int argc, char* argv[])
{
    char *file1, *file2, *file3;
    long num = 0;

    if ( argc > 1 )
    {
        file1 = malloc( strlen( argv[1] ) + 1 ); 
        strcpy( file1, argv[1] );
    }

    if ( argc > 2 )
    {
        file2 = malloc( strlen( argv[2] ) + 1 ); 
        strcpy( file2, argv[2] );
    }

    if ( argc > 3 )
    {
        file3 = malloc( strlen( argv[3] ) + 1 ); 
        strcpy( file3, argv[3] );
    }

    if ( argc > 4 )
    {
        num = strtol( argv[4], NULL, 0 );
    }

    //...

Upvotes: 3

Related Questions