我已经创建了一个命令行工具应用程序(Xocde --> 新应用程序 --> 命令行工具),它运行正常。现在我想通过终端运行它并传递一些命令行参数,如下所示:
int main(int argc, const char * argv[])
{
std::cout << "got "<<argc<<" arguments";
for ( int i = 0; i<argc;i++){
std::cout << "argument:"<<i<<"= "<<argv[i];
}
//// some other piece of code
}
如果我在终端中输入:
open VisiMacXsltConverter --args fdafsdfasf
我得到以下输出:
有 1 个参数参数:0= /Applications/VisiMacXsltConverte
我想知道通过命令行传递参数的正确方法是什么。
当我尝试
open AppName --rwqrw
open: unrecognized option `--rwqrw'
Usage: open [-e] [-t] [-f] [-W] [-R] [-n] [-g] [-h] [-b <bundle identifier>] [-a <application>] [filenames] [--args arguments]
Help: Open opens files from a shell.
By default, opens each file using the default application for that file.
If the file is in the form of a URL, the file will be opened as a URL.
Options:
-a Opens with the specified application.
-b Opens with the specified application bundle identifier.
-e Opens with TextEdit.
-t Opens with default text editor.
-f Reads input from standard input and opens with TextEdit.
-F --fresh Launches the app fresh, that is, without restoring windows. Saved persistent state is lost, excluding Untitled documents.
-R, --reveal Selects in the Finder instead of opening.
-W, --wait-apps Blocks until the used applications are closed (even if they were already running).
--args All remaining arguments are passed in argv to the application's main() function instead of opened.
-n, --new Open a new instance of the application even if one is already running.
-j, --hide Launches the app hidden.
-g, --background Does not bring the application to the foreground.
-h, --header Searches header file locations for headers matching the given filenames, and opens them.
答案1
不要用open
它来启动命令行应用程序。它应该用来运行包装在应用程序包中的 OS X 应用程序。启动服务无法将您的程序识别为应用程序,只需尝试运行open -a VisiMacXsltConverter
...
只需指定其(绝对或相对路径),这样就不会在 中搜索它$PATH
。以下任一方法都可以工作,当然取决于您当前的工作目录和程序的存储位置:
./VisiMacXsltConverter a "b c"
/Users/rohan/Documents/VisiMacXsltConverter/VisiMacXsltConverter a "b c"
答案2
为了解决您的问题-不太确定您的错误:
想象一下一个正常的 C/C++“主”类,如下所示:
int main() {}
只需将其替换为
int main(int argc, char* argv[]) {}
您可以通过 argv[i] 来索引参数。请注意,函数调用本身就是一个参数 (argv[0]);
完整示例(将使用消息):
int main(int argc, char* argv[]){
string fileName;
if (argc < 2) { // Remind user of how to use this program
cerr << "Usage: " << argv[0] << " filename" << endl;
return 0;
} else {
fileName = argv[1];
}
}
请注意,使用此方法,您无需在命令行上以“-”作为参数的前缀。您可以选择添加该约定,只需查找“-”并获取其后的字符串即可。
答案3
argc 将始终保存值 1。这就是为什么显示的输出为“got 1”,然后继续循环。本质上,由于 i = 0,它将打印出正在执行的程序的路径,因为 argv 数组始终以位置 0 处的路径开始。argc 仅保存 argv 数组的长度。在第一次循环之后,程序结束并显示正确的输出。
所以对于你的情况我会写:
int main(int argc, const char * argv[])
{
std::cout << "got "<<argc<<" arguments";
for ( int i = 1; i<=argc;i++){
std::cout << "argument:"<<i<<"= "<<argv[i];
}
//// some other piece of code
}