Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reading from argv in C

Tags:

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.

like image 235
laker001 Avatar asked Dec 06 '25 02:12

laker001


2 Answers

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;
}
like image 97
jschultz410 Avatar answered Dec 08 '25 17:12

jschultz410


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 );
    }

    //...
like image 41
Vlad from Moscow Avatar answered Dec 08 '25 17:12

Vlad from Moscow