[英]C Variable from Terminal
I'm writing a program to read a file and display the number of lines and words in said file, simple stuff. 我正在编写一个程序来读取文件,并显示所述文件中的行数和单词数,这很简单。 What I want is to be able to run the program from terminal (running Ubuntu) by simply typing:
我想要的是能够通过简单输入以下命令从终端(运行Ubuntu)运行程序:
count 计数
But I'm not sure how to get the filename into a variable in the C program. 但是我不确定如何将文件名转换为C程序中的变量。 Little help please?
请帮忙吗?
Thanks in advance. 提前致谢。
我认为您正在寻找argv 。
First of all, the name of the command will start with a ./ as in ./count. 首先,命令名称将以./开头,如./count所示。
Secondly, you can pass arguments to it using the argv pointer of type char**. 其次,您可以使用char **类型的argv指针将参数传递给它。
If you type in the command: 如果键入命令:
./count input.dat
You get: 你得到:
argc = 2 //total number of arguments
argv[0] = "./count"
argv[1] = "input.dat"
For example, to get the filename as the second parameter: 例如,要获取文件名作为第二个参数:
int main( int argc, char *argv[] )
{
char fileName[20];
if(argc>1)
{
strcpy(fileName,argv[1]); // if the command typed is "./count <fileName>"
}
//open & read file
return(0);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.