如何处理来自 getopt 的字符

Dav*_*e A 1 c getopt

我不知道我在哪里失踪。我想从命令行中捕获一些字符。我正在使用 getopt 但不确定如何从 optarg 复制。请帮助我,我不太确定 c 中的字符/字符串处理。

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

main(int argc , char *argv[]) {
    char *file;
    int opt;
    while ( ( opt = getopt(argc, argv, "f:") ) != -1 ){
    switch(opt){
        case 'f':
        file=(char *) malloc(2);
        strcpy(file,optarg);
        printf("\nValue of file is %c\n",file);
    break;
    default :
    return(1);
    }
}
return(0);
}
Run Code Online (Sandbox Code Playgroud)

nio*_*nio 5

要修复@claptrap 建议的错误,请替换:

file=(char *) malloc(2);
strcpy(file,optarg);
Run Code Online (Sandbox Code Playgroud)

更安全:

file = strdup(optarg);
Run Code Online (Sandbox Code Playgroud)

它会自动为你分配和复制字符串,不管它有什么长度。您已经在 string.h 中定义了 strdup,您已经包含了它。

使用文件字符串后,您应该使用以下命令将其从内存中释放:

free(file);
Run Code Online (Sandbox Code Playgroud)

Stdup 联机帮助页。还要检查strncpy函数,它比 strcpy 更安全,因为它知道在溢出之前可以将多少字符复制到目标缓冲区中。