views:

51

answers:

2

Hey guys,

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.

+1  A: 

I think you are looking for argv.

Mike Williamson
Ha, didn't even consider that :) Thanks heaps.
mispecialist
A: 

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);
}
Kedar Soparkar