Error check if no user input in command line

Viewed 54

My program takes a file name from the command line and then searches the file applying the median of medians algorithm. I am trying to error check for no input/they press enter before typing anything. I have tried using strcmp to compare argv to \n with no luck as the program will not terminate if there is no value and you press enter.

Below is part of my read_file function:

int* read_file(FILE*fp, char* file_name, int* arr_size){
   int *tempArray = NULL;  // init temp array to store converted values in
   scanf("%s\n", file_name); // scanf for user input filename
   
   if(strcmp(file_name, "\\n") == 0){
      exit(INCORRECT_NUMBER_OF_COMMAND_LINE_ARGUMENTS);
   }

As well as part of main that takes int argc and char*argv[]:

printf("Enter the name of a file w/ the extension: \n");

int* data1 = read_file(fp, argv[0], size); // read integers into array with the beginnging of file(x)
if (strcmp(argv[0], "\\n") == 0){
   exit(INCORRECT_NUMBER_OF_COMMAND_LINE_ARGUMENTS);
}
printf("xth smallest: %d\n", xthSmallest(data1, 0, *size-1, data1[0]));  // print data

Note: the exit command is an enum in the header file

If I change the read_file parameter when I call the function in main, from argv[0] to argv[1], the program seg faults as there is nothing being stored in argv[1] rather, the user input after running ./a.out is stored in argv[0], NOT a.out in argv[0]

1 Answers

What you actually want to be checking in your

if (strcmp(argv[0], "\\n") == 0){
   exit(INCORRECT_NUMBER_OF_COMMAND_LINE_ARGUMENTS);
}

block is something more like

if (argc < 2) {
   exit(INCORRECT_NUMBER_OF_COMMAND_LINE_ARGUMENTS);
}

argc holds the number of arguments you get. argv holds the arguments, where argv[0] is the name of the executable itself.

For example,

foo.exe bar baz biz

would be held as

argv[0] = "foo.exe"
argv[1] = "bar"
argv[2] = "baz"
argv[3] = "biz"

Which means read_file(fp, argv[0], size) should be read_file(fp, argv[1], size). You should also have it after your parameter check for safety.

Related