I am trying to recreate the bash "head" and "tail" commands (which print the contents of files in different ways) using c programs. I figured that the getopt
function would be useful for parsing the command-line options from the files to be printed. Here's what I have so far:
#include <stdio.h>
#include <stdlib.h>
#include <fcntl.h>
#include <unistd.h>
const int BUFFER_SIZE = 100;
int main(int argc, char *argv[]) {
int c = 10;
int n = 0;
int opt;
while ((opt = getopt(argc, argv, "cn:")) != -1) {
switch(opt) {
case 'c':
c = atoi(optarg);
break;
case 'n':
n = atoi(optarg);
break;
}
}
printf("c = %d & n = %d\n", c, n);
}
The program compiles. However, when I run the executable with -c 5
as its command-line arguments, the program crashes. I don't understand what the problem is.
CodePudding user response:
Your optstring ("cn:"
) says that c
does not take an argument, so in this block:
case 'c':
c = atoi(optarg);
printf("worked\n");
break;
optarg
is NULL
, which is why atoi(optarg)
leads to a segmentation fault.
If option -c
takes an argument, then you want:
while ((opt = getopt(argc, argv, "c:n:")) != -1) {