Friday, July 13, 2018

Command Line Arguments in C

Description

It is possible to pass some values from the command line to your C programs when they are executed. These values are called command line arguments and many times they are important for your program especially when you want to control your program from outside instead of hard coding those values inside the code.

The command line arguments are handled using main() function arguments where argc refers to the number of arguments passed, and argv[] is a pointer array which points to each argument passed to the program. Following is a simple example which checks if there is any argument supplied from the command line and take action accordingly −

The arguments passed from command line are called command line arguments. These arguments are handled by main() function.

To support command line argument, you need to change the structure of main() function as given below.





int main(int argc, char *argv[] )



Here, argc counts the number of arguments. It counts the file name as the first argument.

The argv[] contains the total number of arguments. The first argument is the file name always.

Example

Let's see the example of command line arguments where we are passing one argument with file name.





#include <stdio.h>
void main(int argc, char *argv[] )
{

printf("Program name is: %s\n", argv[0]);

if(argc < 2){
printf("No argument passed through command line.\n");
}
else{
printf("First argument is: %s\n", argv[1]);
}
}



Run this program as follows in Linux:

./program hello

Run this program as follows in Windows from command line:

program.exe hello

Output:

Program name is: program

First argument is: hello

If you pass many arguments, it will print only one.

./program hello c how r u

Output:

Program name is: program

First argument is: hello

But if you pass many arguments within double quote, all arguments will be treated as a single argument only.

./program "hello c how r u"

Output:

Program name is: program

First argument is: hello c how r u

You can write your program to print all the arguments. In this program, we are printing only argv[1], that is why it is printing only one argument.





#include <stdio.h>

int main( int argc, char *argv[] ) {

if( argc == 2 ) {
printf("The argument supplied is %s\n", argv[1]);
}
else if( argc > 2 ) {
printf("Too many arguments supplied.\n");
}
else {
printf("One argument expected.\n");
}
}



When the above code is compiled and executed with single argument, it produces the following result.





$./a.out testing

The argument supplied is testing



When the above code is compiled and executed with a two arguments, it produces the following result.





$./a.out testing1 testing2

Too many arguments supplied.



When the above code is compiled and executed without passing any argument, it produces the following result.





$./a.out

One argument expected



It should be noted that argv[0] holds the name of the program itself and argv[1] is a pointer to the first command line argument supplied, and *argv[n] is the last argument. If no arguments are supplied, argc will be one, and if you pass one argument then argc is set at 2.

You pass all the command line arguments separated by a space, but if argument itself has a space then you can pass such arguments by putting them inside double quotes "" or single quotes ''. Let us re-write above example once again where we will print program name and we also pass a command line argument by putting inside double quotes −





#include <stdio.h>

int main( int argc, char *argv[] ) {

printf("Program name %s\n", argv[0]);

if( argc == 2 ) {
printf("The argument supplied is %s\n", argv[1]);
}
else if( argc > 2 ) {
printf("Too many arguments supplied.\n");
}
else {
printf("One argument expected.\n");
}
}



When the above code is compiled and executed with a single argument separated by space but inside double quotes, it produces the following result.

$./a.out "testing1 testing2"

Progranm name ./a.out

The argument supplied is testing1 testing2




Instagram



C #pragma

Description

Pragma directive is a method specified by the C standard for providing additional information to the C compiler.Basically it can be used to turn on or turn off certain features.Pragmas are operating system specific and are different for every compiler.

The #pragma preprocessor directive is used to provide additional information to the compiler. The #pragma directive is used by the compiler to offer machine or operating-system feature.

Syntax:





#pragma token



Different compilers can provide different usage of #pragma directive.

The turbo C++ compiler supports following #pragma directives.





#pragma argsused
#pragma exit
#pragma hdrfile
#pragma hdrstop
#pragma inline
#pragma option
#pragma saveregs
#pragma startup
#pragma warn



Let's see a simple example to use #pragma preprocessor directive.





#include<stdio.h>
#include<conio.h>

void func() ;

#pragma startup func
#pragma exit func

void main(){
printf("\nI am in main");
getch();
}

void func(){
printf("\nI am in func");
getch();
}



Output:

I am in func

I am in main

I am in func

By using #pragma startup directive we can call the functions on startup before main function execution





#include<stdio.h>
void print1()
{
printf("Before Main 1\n");
}
void print2()
{
printf("Before Main 2\n");
}
#pragma startup print1 0
#pragma startup print2 1
int main()
{
printf("In Main\n");
return 0;
}



Output

In Main

This will not work when compiled on gcc as it does not recognize this pragma directive.If we want any function to be called before main function by using gcc we have to use __attribute__((constructor (PRIORITY))





#include<stdio.h>
void print1()__attribute__((constructor(100)));
void print2()__attribute__((constructor(101)));
int main()
{
printf("In Main\n");
}
void print1()
{
printf("Before Main 1\n");
}
void print2()
{
printf("Before Main 2\n");
}



Output

Before Main 1

Before main 2

In Main

Examples of #pragma exit function:

Syntax:#pragma exit function_name priority





#include<stdio.h>
void print1()
{
printf("After Main 1\n");
}
void print2()
{
printf("After Main 2\n");
}
#pragma exit print1 0
#pragma exit print2 1
int main()
{
printf("In Main\n");
return 0;
}



OutPut

In Main

For gcc compiler we have to use __attribute__((destructor(priority)))





#include<stdio.h>
void print1()__attribute__((destructor(100)));
void print2()__attribute__((destructor(101)));
int main()
{
printf("In Main\n");
}

void print1()
{
printf("Before Main 1\n");

}

void print2()
{
printf("Before Main 2\n");
}



Output

Before Main 2

Before Main 1




Instagram



C #error

Description

In the C Programming Language, the #error directive causes preprocessing to stop at the location where the directive is encountered. Information following the #error directive is output as a message prior to stopping preprocessing.

The #error preprocessor directive indicates error. The compiler gives fatal error if #error directive is found and skips further compilation process.

C #error example

Let's see a simple example to use #error preprocessor directive.





#include<stdio.h>
#ifndef __MATH_H
#error First include then compile
#else
void main()
{
float a;
a=sqrt(7);
printf("%f",a);
}
#endif



Output:

Compile Time Error: First include then compile

But, if you include math.h, it does not gives error.





#include<stdio.h>
#include<math.h>
#ifndef __MATH_H
#error First include then compile
#else
void main(){
float a;
a=sqrt(7);
printf("%f",a);
}
#endif



Output:

2.645751

Example

Let's look at how to use #error directives in your C program.

The following example shows the output of the #error directive:





/* Example using #error directive by c programming */

#include <stdio.h>
#include <limits.h>

/*
* Calculate the number of milliseconds for the provided age in years
* Milliseconds = age in years * 365 days/year * 24 hours/day, 60 minutes/hour, 60 seconds/min, 1000 millisconds/sec
*/
#define MILLISECONDS(age) (age * 365 * 24 * 60 * 60 * 1000)

int main()
{
/* The age of C programming in milliseconds */
int age;

#if INT_MAX < MILLISECONDS(12)
#error Integer size cannot hold our age in milliseconds
#endif

/* Calculate the number of milliseconds in 12 years */
age = MILLISECONDS(12);

printf("TechOnTheNet is %d milliseconds old\n", age);

return 0;
}



In this example, we are using the int data type to hold the age of c programming in milliseconds. The int data type has a maximum value of INT_MAX which is defined in the limits.h header file and holds a value of 2^31 - 1 on both 32 and 64 bit systems. (See here for other variable types and their sizes.)

The statement #if INT_MAX < MILLISECONDS(12) evaluates whether or not the int data type is large enough to store the age in milliseconds. If it is not, the processor will output the following error message:





error: Integer size cannot hold our age in milliseconds



Since an error occurred, the program compilation will not complete and therefore no executable program will be created.

A typical use of the #error directive is to prevent compilation if a known condition exists that would cause the program to not function properly if the compilation completed. (For example, the C source was designed for a specific platform and was being compiled on an incompatible platform.)




Instagram



C #else

Description

In the C Programming Language, the #else directive provides an alternate action when used with the #if, #ifdef, or #ifndef directives. The preprocessor will include the C source code that follows the #else statement when the condition for the #if, #ifdef, or #ifndef directive evaluates to false.

The #else preprocessor directive evaluates the expression or condition if condition of #if is false. It can be used with #if, #elif, #ifdef and #ifndef directives.

Syntax:





#if expression
//if code
#else
//else code
#endif



Syntax with #elif:





#if expression
//if code
#elif expression
//elif code
#else
//else code
#endif



Note

  • The #else directive must be closed by an #endif directive.

C #else example

Let's see a simple example to use #else preprocessor directive.





#include <stdio.h>
#include <conio.h>
#define NUMBER 1
void main() {
#if NUMBER==0
printf("Value of Number is: %d",NUMBER);
#else
print("Value of Number is non-zero");
#endif
getch();
}



Output:

Value of Number is non-zero

Example

The following example shows how to use the #else directive in the C language:





/* Example using #else directive by c programming */

#include <stdio.h>

#define YEARS_OLD 12

int main()
{
#if YEARS_OLD < 10
printf("c programming is a great resource.\n");
#else
printf("TechOnTheNet is over %d years old.\n", YEARS_OLD);
#endif

return 0;
}



Here is the output of the executable program:

c programming is over 12 years old.




Instagram