0

当我运行我的程序./program a b c d而不是

./program -i inFile -o outFile

它告诉我文件打开有问题(这是真的)但是

Expected: "Usage: program -i inputfile -o outputfile\n"
Got: "Error: Cannot open file /no/such/file\n" 

你知道我该怎么处理吗?有什么线索吗?这也是我处理错误参数处理的代码的一部分:

if ((s= strrchr( argv[0], '\\')) /* get filename w/o .exe extension */
                  || (s= strrchr( argv[0], '/')))
              s++;
        else
              s= argv[0];
        if(inFile == NULL || outFile == NULL) {
        error_usage(s);
         }
        if ( argc !=5 )
           {
             error_usage(s);
             return -1;
           }
        while ((c = getopt(argc, argv, "i:o:")) != -1) {
            switch (c) {


         case 'i':
                          inFile = strdup(optarg);
                 break;
                 case 'o':
                          outFile = strdup(optarg);
                 break;
                 default:

                          error_usage(s);

                      }
                }

      if (!(iFile = fopen(inFile, "r+"))) {
      fprintf(stderr, "Error: Cannot open file %s\n", inFile);
      exit(1);
   }
4

2 回答 2

2

Well all I can do is repeat the answer to your earlier question, which I think was the correct answer all along.

See inFile and outFile to NULL, then after your getopts loop check to see if either is still NULL. If they are then print the usage message and exit

    inFile = outFile = NULL;
    while ((c = getopt(argc, argv, "i:o:")) != -1) {
        switch (c) {
        case 'i':
            inFile = strdup(optarg);
            break;
        case 'o':
            outFile = strdup(optarg);
            break;
        default:
            error_usage(s);
        }
    }
    if (inFile == NULL || outFile == NULL)
        error_usage(s);

You placed the check on inFile and outFile in the wrong place in your code. It should go after the while loop. What you are doing is checking if the earlier while loop sets the values of both inFile and outFile and complaining to the user if it does not. And as I said before I don't think if (argc != 5) is helpful, I would just delete it.

于 2013-09-23T06:15:47.323 回答
0

Getopt doesn't know about "mandatory" arguments. It will parse all the arguments it can find, but it is your responsibility to check the higher-level logic, i.e. whether a consistent set of arguments has been supplied, etc.

Also, you don't generally need to copy strings, since the original string will always be there. The following might work just fine:

char const * infile = NULL;

// ...

case 'i':
    infile = optarg;
    break;

// ....

if (!infile)
{
    puts("Error, you must specify an input file. Use -h for help.\n");
    exit(EXIT_FAILURE);
};
于 2013-09-23T06:15:36.500 回答