-2

I'm working on a socket program. I need to get informations regarding the adress of a server from a document. I need to be able to change what document I get those informations from when I run the executable. For example, if my program is called client.c, I need to be able to type in the terminal : ./client -c Name_Of_The_Document, and then the program will get these informations from the document Name_Of_The_Document.

I have no idea how to implement this "-c" option and I don't even know what to type on google or anything. Thanks to anyone that could help me

I have all the code to read in the document working, I just need to know how to change what document I want to read in form the terminal when running the executable.

jww
  • 97,681
  • 90
  • 411
  • 885
  • 3
    https://linux.die.net/man/3/getopt – Sourav Ghosh Apr 05 '19 at 13:34
  • Look up libpopt and argp_parse – William Pursell Apr 05 '19 at 13:35
  • If you only ever need the file name (i.e. no other options possibly needed) then you could find a simpler solution thatn getopt. Do you need more possible options or not? The answer to that does for example make the difference of which of the currently existing answers is more appropriate. – Yunnosch Apr 05 '19 at 13:38
  • 1
    Possible duplicate of [Argument-parsing helpers for C on Linux](https://stackoverflow.com/q/189972/608639), [Parsing command-line arguments in C?](https://stackoverflow.com/q/9642732/608639), etc. – jww Apr 05 '19 at 13:49
  • 2
    Possible duplicate of [Parsing command-line arguments in C?](https://stackoverflow.com/questions/9642732/parsing-command-line-arguments-in-c) – Mark Benningfield Apr 05 '19 at 13:52

2 Answers2

0

You need to use getopt function. Here is an example:

#include <ctype.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>

int
main (int argc, char **argv)
{
  char *cvalue = NULL;
  int index;
  int c;

  opterr = 0;

  while ((c = getopt (argc, argv, "c:")) != -1)
    switch (c)
      {
      case 'c':
        cvalue = optarg;
        break;
      case '?':
        if (optopt == 'c')
          fprintf (stderr, "Option -%c requires an argument.\n", optopt);
        else if (isprint (optopt))
          fprintf (stderr, "Unknown option `-%c'.\n", optopt);
        else
          fprintf (stderr,
                   "Unknown option character `\\x%x'.\n",
                   optopt);
        return 1;
      default:
        abort ();
      }

  printf ("cvalue = %s\n", cvalue);

  for (index = optind; index < argc; index++)
    printf ("Non-option argument %s\n", argv[index]);
  return 0;
}
Mikhail Vladimirov
  • 13,572
  • 1
  • 38
  • 40
0

If you declare your main() function as

int main (int argc, char *argv[])
{

   return 0;
}

arguments passed to your program will appear in the argv parameters as strings. An example of how to query them is given here.

You can then implement the code which handles opening and reading the file.