Command Line Arguments and flags

How would I go about using command line arguments in order to compare two different text files that will output the following?:

differ -a file1.txt file2.txt
displays all differences
differ -n file1.txt file2.txt
displays the first n differences
And, for example
differ -20
displays the first 20 differences and prompts the user for the file names


A template with explanation would be the most useful. I have some code I am trying to edit in order to do this, but I really want to understand how this works.
You are looking for argc and argv. Argc contains the number of command-line arguments. Argv contains an array (size = argc) of c-strings.

argv[0] is always the name of your application and argc is therefore always a minimum of 1.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
int main(int argc, char* argv[])
{
    std::string file1, file2;
    if (argc < 2)
    {
        cout << "Usage: differ.exe [-a -#] [file1] [file2]" << endl;
        return 1;
    }

    if (argc < 4)
    {
        cout << "Enter a filename: ";
        cin >> file2;
    }
    else
    {
        file2 = argv[3];
    }

    if (argc < 3)
    {
        cout << "Enter a filename: ";
        cin >> file1;
    }
    else
    {
        file1 = argv[2];
    }

    switch(argv[1])
    {
    case "-n": // Do something
    case "-a": // Do something
    }
    return 0;
}
Last edited on
You can't do that with a switch. And you are comparing pointers, no strings.

You could take a look at getopt(). Changing -20 to -n 20
Or just traverse the arguments looking for an starting dash, that would be a flag.
Topic archived. No new replies allowed.