You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Kali Linux下C语言命令行参数问题:--show参数失效排查

问题分析与修复:命令行参数--show无法生效的C程序问题

核心错误点

你的程序出现问题有两个关键原因:

  • strcmp判断逻辑颠倒:strcmp函数在两个字符串完全相等时返回0,不相等时返回非0值。你代码里的if(strcmp(argv[1],show))是当字符串不相等时才执行文件显示逻辑,这和预期完全相反——输入--show时,strcmp返回0,条件不成立,直接进入else分支提示帮助;而输入show时,strcmp返回非0,条件成立才执行显示。
  • 字符串数组长度不足:char show[6] = "--show"; 中,"--show"包含6个可见字符(-、-、s、h、o、w),C语言字符串需要额外的\0作为结束标记,所以至少需要7字节的数组空间。数组长度设为6会导致\0无法存储,造成strcmp比较时的未定义行为。

修复后的完整代码

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

int main(int argc, char *argv[]){
    // 用const char*定义参数字符串,避免数组长度问题,更符合规范
    const char *show = "--show";
    const char *copy = "--copy";
    const char *help = "-h";

    if(argc == 3){
        // 处理--show参数:判断strcmp返回0(字符串相等)
        if(strcmp(argv[1], show) == 0){
            FILE *sfile = fopen(argv[2], "r");
            // 增加文件打开失败的错误处理
            if(sfile == NULL){
                perror("Failed to open file");
                exit(EXIT_FAILURE);
            }
            char ch;
            while((ch = fgetc(sfile)) != EOF){
                if(ferror(sfile)){
                    perror("Read error");
                    break;
                }
                printf("%c", ch);
            }
            fclose(sfile);
            exit(EXIT_SUCCESS);
        }
        else{
            puts("Invalid parameter. Use -h for help.\n");
        }
    }
    // 处理--copy需要4个参数的情况
    else if(argc == 4 && strcmp(argv[1], copy) == 0){
        FILE *src = fopen(argv[2], "r");
        FILE *dest = fopen(argv[3], "w");
        if(src == NULL || dest == NULL){
            perror("Failed to open file");
            exit(EXIT_FAILURE);
        }
        char ch;
        while((ch = fgetc(src)) != EOF){
            if(ferror(src) || ferror(dest)){
                perror("I/O error");
                break;
            }
            fputc(ch, dest);
        }
        fclose(src);
        fclose(dest);
        exit(EXIT_SUCCESS);
    }
    // 处理-h参数或参数数量错误
    else if(argc == 2 && strcmp(argv[1], help) == 0){
        puts("Usage:\n");
        puts("  ./chandu --show <filename>    Show content of the file");
        puts("  ./chandu --copy <srcfile> <destfile>    Copy content from srcfile to destfile");
        puts("  ./chandu -h    Show this help message");
        exit(EXIT_SUCCESS);
    }
    else{
        puts("Invalid argument count. Use -h for help.\n");
        exit(EXIT_FAILURE);
    }
}

额外优化建议

  • 使用const char*定义参数字符串,彻底避免数组长度不足的问题,同时更符合C语言字符串的使用规范。
  • 增加文件打开失败的错误处理,避免空指针访问导致的程序崩溃。
  • 完善参数数量的判断逻辑(比如--copy需要4个命令行参数),并补充清晰的帮助信息输出。

内容的提问来源于stack exchange,提问作者n00bie256

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.08 08:30:58