简体   繁体   English

Kali Linux 中 C 语言的命令行参数问题?

[英]Command-Line Arguments Problem in C-language in Kali Linux?

I am trying to develop a program that will display contents of a file and copies content of file1.txt to file2.txt in kali linux using command-line arguments.我正在尝试开发一个程序,该程序将显示文件内容并使用命令行参数将 file1.txt 的内容复制到 kali linux 中的 file2.txt。 Here is the code:这是代码:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main(int argc, char *argv[]){`

    char show[6] = "--show";
    char copy[6] = "--copy";
    char help[2] ="-h";

    if(argc == 3){
        // chandu --show filename
        if(strcmp(argv[1],show)){ // strcmp => compares two strings.
            FILE *sfile;
            char ch;
            sfile=fopen(argv[2],"r");
            while((ch = fgetc(sfile)) != EOF){
                if(ferror(sfile)){
                    perror("I/W");
                    break;
                }
                else{
                    printf("%c",ch);
                }
            }
            fclose(sfile);
            exit(0);
        }else{
            puts("use -h for help.\n");
        }
    }

Problem is: Displaying content must work with ./chandu --show meow.txt but it works with ./chandu show meow.txt .Means with double hyphen (--) it does'nt work and without hyphen, it works.问题是:显示内容必须与./chandu --show meow.txt工作,但它与./chandu show meow.txt一起工作。意味着使用双连字符 (--) 它不起作用,没有连字符,它工作。 Why?为什么? I can't figure it out.我想不通。 Please help.请帮忙。

I changed strcmp() to strncmp() so that it could run (hit-trial method) but it didn't.我将strcmp()更改为strncmp()以便它可以运行(命中试验方法)但它没有。

strcmp returns 0 is the two strings are equal, and 0 means the if 's condition won't be executed. strcmp返回 0 表示两个字符串相等, 0表示执行if的条件。 You could explicitly compare the result to 0 :您可以明确地将结果与0进行比较:

if(strcmp(argv[1], show) == 0) {
  // Here ---------------^

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

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