tags:

views:

30

answers:

2

Below is the code of main() of grub. Here I want to know about this line:

file = fopen(arg_v[1], "rb");

Here which file fopen is opening? What file this arg v[1] is pointing to?

int main(unsigned arg_c, char *arg_v[])    
{    
    FILE *file;    

    if(arg_c < 2)    
    {    
        printf("Checks if file is Multiboot compatible\n");    
        return 1;    
    }    
    file = fopen(arg_v[1], "rb");    
    if(file == NULL)    
    {    
        printf("Can't open file '%s'\n", arg_v[1]);    
        return 2;    
    }    
    check_multiboot(arg_v[1], file);    
    fclose(file);    
    return 0;    
}
+1  A: 

arg_v is a pointer to an array of pointers to strings passed to the program when main is invoked. arg_v[1] is hence a pointer to the first string passed to the program when it is invoked (even though the array starts at 0; the 0'th element is the program name itself).

Edit: So to be concrete, if the above is the main function of an executable invoked as grub foo bar, then arg_v[0] points to the string "grub" and arg_v[1] points to "foo". Hence the fopen call will try to open a file named "foo".

gspr
+2  A: 

If you call your program with

program arg1 arg2.txt 65

argv[1] is a pointer to "arg1"; argv[2] is a pointer to "arg2.txt", argv[3] is a pointer to "65", argv[4] is NULL

argv[0] either points to "program" or to "" if the OS and/or Library and/or startup code cannot identify the name used to call the binary executable

In your specific case, the program tries to open a file, whose name is provided in the first argument to the program, in read binary mode.

pmg
The usual names of the variables are `argc` and `argv`. **There is nothing wrong about giving them other names**, it just makes it unusual *and unusual is not good*
pmg
Thanks, I understood.