Convert command line argument to string

后端 未结 7 1170
囚心锁ツ
囚心锁ツ 2021-01-31 08:43

I have a program that reads hard-coded file-path and I want to make it read file-path from command line instead. For that purpose I changed the code like this:

#         


        
相关标签:
7条回答
  • 2021-01-31 09:16

    I'm not sure if this is 100% portable but the way the OS SHOULD parse the args is to scan through the console command string and insert a nil-term char at the end of each token, and int main(int,char**) doesn't use const char** so we can just iterate through the args starting from the third argument (@note the first arg is the working directory) and scan backward to the nil-term char and turn it into a space rather than start from beginning of the second argument and scanning forward to the nil-term char. Here is the function with test script, and if you do need to un-nil-ify more than one nil-term char then please comment so I can fix it; thanks.

    #include <cstdio>
    #include <iostream>
    
    using namespace std;
    
    namespace _ {
    /* Converts int main(int,char**) arguments back into a string.
    @return false if there are no args to convert.
    @param arg_count The number of arguments.
    @param args      The arguments. */
    bool ArgsToString(int args_count, char** args) {
      if (args_count <= 1) return false;
      if (args_count == 2) return true;
      for (int i = 2; i < args_count; ++i) {
        char* cursor = args[i];
        while (*cursor) --cursor;
        *cursor = ' ';
      }
      return true;
    }
    }  // namespace _
    
    int main(int args_count, char** args) {
      cout << "\n\nTesting ArgsToString...\n";
    
      if (args_count <= 1) return 1;
      cout << "\nArguments:\n";
      for (int i = 0; i < args_count; ++i) {
        char* arg = args[i];
        printf("\ni:%i\"%s\" 0x%p", i, arg, arg);
      }
      cout << "\n\nContiguous Args:\n";
      char* end = args[args_count - 1];
      while (*end) ++end;
      cout << "\n\nContiguous Args:\n";
      char* cursor = args[0];
      while (cursor != end) {
        char c = *cursor++;
        if (c == 0)
          cout << '`';
        else if (c < ' ')
          cout << '~';
        else
          cout << c;
      }
      cout << "\n\nPrinting argument string...\n";
      _::ArgsToString(args_count, args);
      cout << "\n" << args[1];
      return 0;
    }
    
    0 讨论(0)
提交回复
热议问题