Search code examples
cstringcommand-line-argumentscompiler-warningsstrtol

Casting issues using argument input from C


I am trying to write a C program, where a user must input two arguments into the command line. First, they must provide a name of a text file of values to be read. Second, they must provide a value of 0 or 1, which will be saved as an integer to be used as a boolean (0=false, 1=true).

#include <stdio.h>
#include <string.h>
#include <stdlib.h>

int main(int argc, char *argv[]){
   FILE *f;
   char *fname;
   int boolVal;

  if (argc != 2){
    printf("This program requires two input types, data file and boolean value of 0 or 1\n");
    return 1;
  } 

  fmame = argv[1];
  boolVal = argv[2];
  printf("The file name is %s and the boolVal is %d.\n", fmame, boolVal);

   f = fopen(fname, "r");
   if (f == NULL) perror ("Could not open file");
      else {
         if (fgets(myStr, 1000, f) != NULL )
            puts(myStr);
            fclose(f);
      }
   return 0;
}

I get an error:

testArg.c: In function ‘main’:
testArg.c:16: warning: assignment makes integer from pointer without a cast

I have two questions: Is my reading in of the file name correct? Second, how to solve the issue of casting?


Solution

  • Following your requirement,

    where a user must input two arguments into the command line. First, they must provide a name of a text file of values to be read. Second, they must provide a value of 0 or 1, which will be saved as an integer to be used as a boolean (0=false, 1=true).

    your code should read like

    if (argc != 3)
    {  //code
    

    remember, the binary name also counts. So ./<binary> <filename> <1/0> makes the argc as 3.

    Next, the reason for the warning in your code is for

    boolVal = argv[2];
    

    All the command line inputs are read in a form of string [char *]. You can understand that easily if you check the data type of argv[2]. Isn't it say char *? Then, you need to convert that (alpha)numeric string to an integer value before you assign that value to an int variable.

    So, what you need here is

    boolVal = atoi(argv[2]);
    

    or, even better and recommended,

    boolVal = strtol(argv[2], NULL, 0);    
    

    Please check the man page of strtol() for details.