Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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 ---------------^
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading