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:
count
But I'm not sure how to 开发者_开发技巧get the filename into a variable in the C program. Little help please?
Thanks in advance.
I think you are looking for argv.
First of all, the name of the command will start with a ./ as in ./count.
Secondly, you can pass arguments to it using the argv pointer of type char**.
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);
}
精彩评论