0

I'm trying to parse command line arguments into a parse.c file which loops through all the arguments and then passes them into another file.

I encountered a problem where if the user wanted to search through a specific textfile I don't know if there's any good robust way to check if the argument is a textfile.

Below is what I've done so far. A typical command line could be

./sgrep -i searchstring file.txt

So is there a way for me to 100% identify a file in a command line?

  for (i=0; i<arguments; i++) {
    if (strcmp("-i", args[i])==0) {
      data->case_sensitive = 0; /* set case insensitive */
    } 
    else if((len = strlen(args[i])) > 3 && !strcmp(args[i]+len-4, ".txt")){ 
      data->filename = args[i]; /* store textfile name in filename*/
      } 
    else {
      data->reg_exp = args[i]; /' store searchstring in regexp */
    }
  }
5
  • You mean other than the extension of the filename? I dont sure if you can since .txt files doesn't have any special headers, just a bunch of binary data converted into ASCII or any other encoding of your choosing.
    – NadavL
    Dec 17, 2015 at 20:17
  • If the file is required to exist when it is specified, you can just see if each item that might be a file exists (such as via the access(path, F_OK) function, perhaps using other flags to ensure readability, etc.). Generally though, you should use something like the getopt function to parse your command line, making these things much more simplified.
    – mah
    Dec 17, 2015 at 20:21
  • Try opening the file? Or use stat(). Dec 17, 2015 at 20:22
  • Command line params are only meaningfull to the app it is passed to. There are many ways the app determines what the arg is. Usually by -<letter> param, and usually sequential. Lots of times the filename is last as a standalone param with no id.
    – user557597
    Dec 17, 2015 at 20:23
  • @mah This helped, thank you!
    – felle
    Dec 17, 2015 at 20:53

1 Answer 1

1

I would first make sure the file exists with lstat. Beyond that, I'd say you need to decide whether you care more about false positives or false negatives. Also, you need to decide what you classify as text file. Do you care if there are some text files that get missed if they don't have the .txt extension? If you do, then ditch that check. You could open the file and scan for non-ASCII characters. You could also just look at the first 8 bytes or so looking for non-ASCII to bound the problem.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.