Question

I am not sure where i am missing. I want to catch some characters from command line. I am using getopt but not sure how to copy from optarg. Please help me i am not very sure about character/string handling in c.

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <getopt.h>

main(int argc , char *argv[]) {
    char *file;
    int opt;
    while ( ( opt = getopt(argc, argv, "f:") ) != -1 ){
    switch(opt){
        case 'f':
        file=(char *) malloc(2);
        strcpy(file,optarg);
        printf("\nValue of file is %c\n",file);
    break;
    default :
    return(1);
    }
}
return(0);
}
Was it helpful?

Solution

To fix an error that @claptrap suggests, replace:

file=(char *) malloc(2);
strcpy(file,optarg);

with safer:

file = strdup(optarg);

It will allocate and duplicate the string for you automatically, whatever length it has. You have the strdup defined in string.h which you already have included.

After you use the file string, you should free it from memory using:

free(file);

Strdup manpage. Also check out strncpy function which is safer to use than strcpy, because it knows how many character it can copy into target buffer before overflowing it.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top