BugShotGG
BugShotGG

Reputation: 5190

How to fopen with name already in a array of strings

I am trying to find a way to use FILE * fopen ( const char * filename, const char * mode ); but passing the filename indirectly. i would also like to know how to indirectly call a function with name taken straightly from argv[].I dont want to store the string in a buffer char array. For example:

 int main (int argc,char *argv[])
    {
      FILE *src;
      ...
      src = fopen("argv[1]", "r");   //1st:how to insert the name of the argv[1] for example?
      ...
     function_call(argc,argv);    //2nd:and also how to call a function using directly argc argv
     ...
     }
    void create_files(char name_file1[],char name_file2[])
    {...}

Do i have to store length and the string of chars in order to call a function? (regarding the 2nd question) :)

Upvotes: 0

Views: 5797

Answers (2)

Matt Joiner
Matt Joiner

Reputation: 118710

fopen takes a pointer to an array of characters. argv is pointer to an array of pointers to arrays of characters.

fopen(argv[1], "r")

will pass the pointer in the second position of the argv array to fopen.

If you want to pass argc and argv around, just pass them as they are. Their types do not change.

Upvotes: 1

cnicutar
cnicutar

Reputation: 182754

You can simply use argv[1], it's a char *:

if (argc < 2)
    /* Error. */

src = fopen(argv[1], "r");

Same goes for create_files.

create_files(argv[1], argv[2]);

Upvotes: 4

Related Questions