felle
felle

Reputation: 11

Parse a filename from command line C

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 */
    }
  }

Upvotes: 0

Views: 473

Answers (1)

Turn
Turn

Reputation: 7030

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.

Upvotes: 1

Related Questions