简体   繁体   English

从主函数向用户定义C函数传递命令行参数

[英]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)传递给名为(GetFile)的用户定义函数:我试过了:

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 用户定义的函数从Main函数获取根名文件,将其复制并与调用函数传递的扩展名连接

How do i pass the value of rootName value to GetFile function outside my main function.Any help is appreciated 我如何将rootName值的值传递到主函数之外的GetFile函数。感谢您的任何帮助

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. 注意:尽管不是错误,但C的标准编码样式避免使用caMelCaseMixedCase变量名,而支持所有小写字母,同时保留大写字母名称以供宏和常量使用。 It is a matter of style -- so it is completely up to you. 这是风格问题-因此完全取决于您。 See eg NASA - C Style Guide, 1994 参见例如NASA-C样式指南,1994年

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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