Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

C, convert an char argv[] argument to char[] makes gibberish

I am trying a C program and a part of it is taking file names as arguments, but when I try to convert them from the argument char *argv[] to char fPath[1000] to come out to gibberish.

int main(int argc, char *argv[]) {
    char fPath[1000];
    char uinp[1000];

    // Check for arguments
    if( argc == 2 ) {
        printf("The argument supplied is %s\n", argv[1]);
    } else if ( argc > 1 ) {
        printf("Too many arguments supplied.\n");
        exit(1);
    }


    // Set argv as the file for editing if it is set
    if (argv[1] != NULL) {
    
        printf("argv set = %s", argv[1]);
        char fPath = *argv[1]; <-- This appears to be where the Issues is.
    
    } else {

        printf("File: ");
        scanf("%s", fPath);

    }

After that it makes a file that is supposed to be the name of the argument given but instead it makes one named like "M'$'\026''b'$'\374\177" but in the program the you can only see the b.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

char fPath = *argv[1]; <-- This appears to be where the Issues is.

You declare another variable fPath having type char and assigning the first letter of the second element of the argv. This fPath ends its life when the if completes.

Basically the whole if makes no sense and the code in else invokes undefined behaviour as fPath is not initialized.

You need to copy the string.

int main(int argc, char *argv[]) {
    char fPath[1000];
    char uinp[1000];

    // Check for arguments
    if( argc == 2 ) 
    {
        // Set argv as the file for editing if it is set
        if (argv[1] != NULL) 
        {
            printf("argv set = %s\n", argv[1]);
            strcpy(fPath, argv[1]);
    
            printf("File: ");
            scanf("%s\n", fPath);
        }
    }
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading