cparametersmingwprogram-entry-pointwildcard-expansion

C main parameter


I wrote a code which has to display main parameters, but when I compiled it and typed in "*" program shows my file structure. Command in cmd looks like this: program.exe 1 2 3 *

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

int main(int argc, char const* argv[]) {
    for (int i=0; i<argc; i++) printf("%s\n", argv[i]);
    return 0;
}

The result is:

program
1
2
3
program.c
program.exe
10-03-20
11-02-20

And my question: Is it possible to force program to print "*" instead of listing files.


Solution

  • mingw causes the program to perform wildcard expansion of the parameters. Add the following to your program to disable this behaviour:

    int _CRT_glob = 0;
    

    In the unix world, the shell is expected to perform wildcard expansion.

    $ perl -le'print for @ARGV' *
    a
    b
    

    In the Windows world, wildcard expansion is left to the application.

    >perl -le"print for @ARGV" *
    *
    

    That makes writing portable programs tricky. Since mingw is often used to compile programs that weren't written with Windows in mind, its C runtime library performs wildcard expansion of the parameters automatically.

    a.c:

    #include <stdio.h>
    
    int main(int argc, char const* argv[]) {
        for (int i=0; i<argc; i++)
            printf("%s\n", argv[i]);
    
        return 0;
    }
    
    >gcc -Wall -Wextra -pedantic-errors a.c -o a.exe & a *
    a
    a.c
    a.exe
    

    But, mingw provides an out. Adding the following to your program disables this behaviour:

    int _CRT_glob = 0; 
    

    a.c:

    #include <stdio.h>
    
    int _CRT_glob = 0; 
    
    int main(int argc, char const* argv[]) {
        for (int i=0; i<argc; i++)
            printf("%s\n", argv[i]);
    
        return 0;
    }
    
    >gcc -Wall -Wextra -pedantic-errors a.c -o a.exe & a *
    a
    *