Home > database >  Command-Line Arguments Problem in C-language in Kali Linux?
Command-Line Arguments Problem in C-language in Kali Linux?

Time:12-16

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. 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. 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.

CodePudding user response:

strcmp returns 0 is the two strings are equal, and 0 means the if's condition won't be executed. You could explicitly compare the result to 0:

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