简体   繁体   中英

passing command line argument from main function to user define C function

i need to pass command line argument from main function (main ) to user defined function called (GetFile) : i tried this:

Main function:

FILE *GetFile(String Extension, String RW);

int main(int argc, char** argv) 
{
File *p
char *rootName = argv[1];
p= GetFile( ".name", "r");
if (p)
{   Do some Stuff!! }
 return 0;
}

User Defined function :

FILE *GetFile(String Extension, String RW)   
{
char  Fn[512];  
strcpy(Fn, rootName);
strcat(Fn, Extension);
return fopen(Fn, RW);
}

User defined function takes rootname file from Main function.copy it and concatenate with the extension passed by calling function

How do i pass the value of rootName value to GetFile function outside my main function.Any help is appreciated

Continuing from the comments, you must be close. Here is an example with the function declaration and definition cleaned up into a working example:

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

FILE *getfile (char *rn, char *ext, char *rw);

int main (int argc, char **argv) 
{
    FILE *p;
    char *rootname = argc > 1 ? argv[1] : "somefile";

    p = getfile (rootname, ".name", "r");
    if (p)
        printf ("file open for reading!\n");
    else
        fprintf (stderr, "error: file open failed.\n");

    return 0;
}

FILE *getfile (char *rn, char *ext, char *rw)   
{
    char fn[512] = "";

    if (!rn || !*rn || !ext || !*ext || (*rw != 'r' && *rw != 'w')) {
        fprintf (stderr, "getfile() error: invalid parameter.\n");
        return NULL;
    }

    strcpy (fn, rn);
    strcat (fn, ext);

    printf ("opening: %s, filemode: %s\n", fn, rw);

    return fopen (fn, rw);
}

Example File

$ touch myfile.name

Example Use/Output

$ ./bin/fileopenfn myfile
opening: myfile.name, filemode: r
file open for reading!

Example with Unmatched Filename

$ ./bin/fileopenfn
opening: somefile.name, filemode: r
error: file open failed.

Look things over and let me know if you have further questions.

Note: While not an error, the standard coding style for C avoids the use of caMelCase or MixedCase variable names in favor of all lower-case while reserving upper-case names for use with macros and constants. It is a matter of style -- so it is completely up to you. See eg NASA - C Style Guide, 1994

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM