0

I'm a bit confused as to how I could add certain parameters in the Ubuntu terminal when using the GNU C compiler to compile the program. For example:

gcc -o question question.c
./question -e -f someFile.txt 

where -f would open this specific file 'someFile.txt' (any file) and -e would let me access a specific function inside my code. I tried this with void main(int argc, char* argv[]) but with that I would have to specify the number of arguments I would have to pass i.e. ./question 3 -e -f resources.txt, which I would not like to do.
Is there any other way I could attempt this? Thank you in advance!!!

shiz
  • 49
  • 6
  • 1
    *"I would have to specify the number of argument"* Uhm, no. The number is determined automatically. – HolyBlackCat May 29 '22 at 09:12
  • @HolyBlackCat would argv[2] not just print -e? – shiz May 29 '22 at 09:15
  • 1
    For `./question -e -f someFile.txt`, `argv[0]` is `./question`, `argv[1]` is `-e`, `argv[2]` is `-f`, etc. – HolyBlackCat May 29 '22 at 09:16
  • You cannot pass _runtime_ arguments to a program at _build_ time. That makes no sense. Clearly this is an XY problem. Ask a question about your actual problem, not about your flawed solution. That is, ask about how to process command line arguments, specify the arguments you wish to pass, and what you want the arguments to do. Clearly you are under a complete misapprehension regarding argv/argc. – Clifford May 29 '22 at 09:24
  • It would not print anything unless your code printed it. It is there as a string in `argv[1]` (not 2) for your code to parse as required. – Clifford May 29 '22 at 09:28
  • Note also, it has nothing to do with Ubuntu or the Terminal, this is standard behaviour for any C code in any platform. The OS is simply required to provide the argv string vector and an argc count to the program. – Clifford May 29 '22 at 09:31
  • @Clifford You're absolutely right, I just started c, so I have muddled concepts. I'm making an effort to fix that right now. Thank you for the detailed input! – shiz May 29 '22 at 10:35

1 Answers1

3
#include <stdio.h>

int main(int argc, char **argv) {
    printf("program was supplied %d arguments.\n", argc - 1);
    for (int k = 0; k < argc; k++) printf("argv[%d] is %s\n", k, argv[k]);
    if (!strcmp(argv[1], "-e")) printf("The first argument provided is -e\n");
}

For advanced usage you may want to read about getopt

pmg
  • 106,608
  • 13
  • 126
  • 198