c - 如何在 argc 和 argv 中分配字符串

标签 c linux

我正在编写一个用户验证程序,成功登录后我提供了一个类似 shell 的提示:

int main()
{
    int argc;
    char **argv;
    char *username = malloc(50);
    char *passwd = malloc(32);
    char command[200];

    printf("Enter username:");
    scanf("%s", username);
    printf("\n");

    printf("Enter password:");
    get_passwd(passwd); //User defined function for taking the password without echoing.

// Then a authentication module is called;
    int success =  authenticate_user(username, passwd);

//After successful authentication of user I will print like:

    printf("test @ %s >", username);

// To look user that he is working on program's own terminal where user can input some command as string

   gets(command);

//Here is the main problem
// I tried using strtok() and g_shell_parse_argv () but not getting the desired result.
   return 0;

}

其他团队成员根据命令字符串解析编写了进一步操作的程序。他们表示我必须了解如何将其解析为 argc 和 argv 变量,就像 main(int argc, int **argv) 函数签名形式变量中一样。

是否有任何 C 库可以做到这一点,或者有任何最佳实践提示或示例可以继续。

Finally I have to parse a string in argc and argv.

非常感谢任何帮助。 谢谢。

最佳答案

  • 对于命令行参数,您必须使用它,

    int main(int argc, char **argv)
    
  • 在您的代码中,您可以这样做。

    int main(int argc, char **argv)
    {
       //your remaining code
       int success =  authenticate_user(argv[1], argv[2]);
    }
    
  • 例如,当您运行像这样的程序时,

    ./demo username password  (./demo abhijatya 1234)
    
  • 因此, argv[0] = ./demoargv[1] = 用户名(abhijatya )argv[2] = 密码(1234).

关于c - 如何在 argc 和 argv 中分配字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35152305/

相关文章:

C 按位或意外更改值

c++ - CPack 具有自己依赖项的多个包

无法评论//代码块

python - 如何等待子进程?

linux - 如何在不使用find的情况下获取当前目录的直接子目录中名称包含某种模式的所有文件?

c - C 中的冒泡排序算法

mysql - 使用返回数组的库函数

c - 一行 C 程序包含?

c - gsoap 生成的 wsdl 无法与 eclipse WebServices explorer 一起使用

linux - 终端 - 当前目录符号