Search code examples
cgetopt

C programming - getopt


When I use the -f I get an error segmentation fault, any ideas? the -f option is for choosing an input file.

  struct list_names filenames;
  list_names_init(&filenames, "filenames");

  optind = 1;
  while ((ch = getopt(argc, argv, ":hvf:")) != -1)  //where getopt defined
    {
      switch (ch) {
        case 'h':
                printf("usage: ./hake [-h] [-v] [-f file]\n-h           print help\n-v           verbose mode; enable extra printing; can be repeated\n");
                printf("-f file      input filename; default is hakefile or Hakefile");
          break;
        case 'v':
          verbose = 1;
          break;
        case 'f':
          f_flag++;
          list_names_append_from_file(&filenames, optarg);
       printf("Read_file%s\n",optarg);
       read_file(optarg);
          break;

Solution

  • Without knowing how list_names_append_from_file is defined it is hard to answer your question. However, a segmentation fault means that you're almost certainly passing the wrong type or number of parameters to a function or that you're messing up a pointer. I'd suggest recompiling (presuming you're using gcc) with -Wall -Werror and see if the compiler doesn't tell you what's going wrong immediately.