To achieve the goal, we will pass the prefix to compare your program as an argument in the command line. This being the case, the answer to your question is actually made up of 2 parts.
The first is
Read the command line arguments
When you write the main function of a C program, you usually see one of these two definitions:
-
int main(void)
-
int main(int argc, char **argv)
The second form receives the arguments that have been passed to the program from the command line, and the number of arguments specified (the arguments are separated by spaces).
Thus, the arguments of main
are:
-
int argc
- The number of arguments that have been passed to the program when it is executed. That value is at least 1
.
-
char **argv
- It is a pointer to char *
. Alternatively it can be: char *argv[]
, which means an 'array of char *
'. This is an array of pointers to strings ending in null.
Basic example:
For example, you could print the arguments that your program receives with this program:
#include <stdio.h>
int main(int argc, char **argv)
{
for (int i = 0; i < argc; ++i)
{
printf("argv[%d]: %s\n", i, argv[i]);
}
}
Using GCC 4.5 to compile this code into a file called args.c
would default to an executable called a.out
.
[jachguate@lilun c_code]$ gcc -std=c99 args.c
When executing it ...
[jachguate@lilun c_code]$ ./a.out hello there
argv[0]: ./a.out
argv[1]: hello
argv[2]: there
As you can see, in argv
, the first element argv[0]
is the name of the program itself (it is not something that is defined in a standard, but it is common that it works). The arguments you received are in argv[1]
and following.
This is pretty rudimentary, but it works for simple cases (like this one).
The other part is:
Compare if a character string starts with another:
Once you have the argument, now basically we need to know if the name of the interface that we are processing within the cycle while
, stored in ifa_name
starts with said prefix , for that we can make use of of the strncmp
function, which basically compares the first n bytes of two strings and returns 0 if the strings They are equal. The way to call it would be with an if, in a structure similar to this:
if strncmp(prefijo, cadena, strlen(prefijo)) == 0 {
printf("cadena SI inicia con prefijo!");
}
Now let's put the pieces together
Putting this together in code is a task left to the reader, but basically what I would do is follow the following steps:
- Check the number of arguments received. If no argument has been passed to the program, inform the user of the form of use and exit with error (the result of main could be 1 and not 0, for example)
- Within the while, add with a logical operator
&&
(and) the comparison condition with the prefix, at the end of the if
already existing. So that only those that meet all the conditions are printed.