0

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.

2 Answers 2

1

I think you are looking for argv.

Sign up to request clarification or add additional context in comments.

1 Comment

Ha, didn't even consider that :) Thanks heaps.
0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.