0% found this document useful (0 votes)
63 views

Unit 5 PWC

The document discusses C preprocessor directives and files. It describes: 1) The C preprocessor is a separate step from compilation that operates on preprocessor directives like #include, #define, #if etc. before the compiler runs. 2) Common preprocessor directives include #include to insert header files, #define for macros, and #if/#else/#endif for conditional compilation. 3) Macros can be simple constants or more complex macros with arguments, and can be undefined with #undef. Conditional compilation allows certain code blocks to be included or excluded based on conditions.

Uploaded by

Guru Rockzz
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
63 views

Unit 5 PWC

The document discusses C preprocessor directives and files. It describes: 1) The C preprocessor is a separate step from compilation that operates on preprocessor directives like #include, #define, #if etc. before the compiler runs. 2) Common preprocessor directives include #include to insert header files, #define for macros, and #if/#else/#endif for conditional compilation. 3) Macros can be simple constants or more complex macros with arguments, and can be undefined with #undef. Conditional compilation allows certain code blocks to be included or excluded based on conditions.

Uploaded by

Guru Rockzz
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 29

16GET26-C Programming I CSE

C Preprocessor Unit V- Preprocessor Directives and Files

 The C Preprocessor is not a part of the compiler, but is a separate step in


the compilation process.

 Commands used in preprocessor are called preprocessor directives and


they begin with hash "#" symbol and should be not ended with (;).

 Compiler examines the preprocessor for any preprocessor directives


 If there is any preprocessor directives, the appropriate actions are taken
and the source program is moved for compilation
 Preprocessors operates under the following preprocessor directives
 File Inclusion
 Macro Expansion/Substitution
 Conditional Compilation

Defined Preprocessor Directive

 Preprocessor Directive can be placed anywhere in the program, but


generally it is placed in the top of the program before defining the first
function.

Example:

#include<stdio.h>
#define PI 3.14
void main()
{
printf("%f",PI);
}
Output

3.14

C language preprocessor directives

 Macro substitution directives.


 example #define

 File inclusion directives.


 example #include
16GET26-C Programming I CSE

 Conditional compilation directive.


 example #if, #else, #ifdef, #undef

 Miscellaneous directive.
 example #error, #line

Preprocessor Syntax Description

Macro #define This macro defines constant value and


can be any of the basic data types.

Header file #include The source code of the file "file_name" is


inclusion <file_name> included in the main program at the
specified place

Conditional #ifdef, #endif, Set of commands are included or


compilation #if, excluded in source program before
compilation with respect to the condition
#else, #ifndef

Other #undef, #pragma #undef is used to undefine a defined


directives macro variable. #Pragma is used to call a
function before and after main function in
a C program

 Program execution needs following steps


 C Program written in editor
 Compilation
 Linking
 Executable code generation
16GET26-C Programming I CSE

File Inclusion
 #include causes the contents of another file to be compiled as if they
actually appeared in place of the #include directive.
 The way this substitution is performed is simple, the Preprocessor
removes the directive and substitutes the contents of the named file.
 Compiler allows two different types of #include’s, first is standard
library header include, syntax of which is as follows,
#include <filename.h>
 Here, filename.h in angle brackets causes the compiler to search for the
file in a series of standard locations specific to implementation.
 For example, gcc compiler on Linux, searches for standard library files
in a directory called /usr/include.
 Other type of #include compiler supports is called local include, whose
syntax is as follows,
#include "filename.h"
 filename in double quotes “” causes compiler to search for the file first
in the current directory and if it’s not there it’s searched in the standard
locations as usual.
 Though, this doesn’t affect runtime efficiency of program, however, it
slows down compilation process. For ex.,
#include "stdio.h"
 Notice here that stdio.h is a standard library file which compiler, has to
search in the current directory before locating it in standard location. A
better reason why library header files should be used with angle
brackets is the information that it gives the reader. The angle brackets
make it obvious that
#include <string.h> references a library file.
 With the alternate form
#include "string.h" it’s not clear if string.h is a library
header or local file with same name is being used
16GET26-C Programming I CSE

Macro Substitution/Expansion

 Used to define symbolic constants in the source program


 Identifier or string or integer defined is replaced by macro substitution

Syntax

#define identifier string/integer

 Preprocessor accomplish the task specified in #define statement


 This statement is also placed before the main() function in source
program

Different forms of Macros

 Simple Macros
 Argumented Macros
 Nested Macros

Simple Macros

 Commonly used to define symbolic constants

Example:
#define age 20
#define CITY “Chennai”
#define g 9.8
#define A 10

Example:
#define A 10-5
#define B 20-10
C=A+B
C=(10-5)+(20-10)
16GET26-C Programming I CSE

Example program to define and create identifiers for C statements and


variables
#define N 10
#define cls clrscr()
#define wait() getche()
#define display printf
void main()
{
int k;
cls;
for(k=1;k<=N;K++)
display(“%d”,k);
wait();
}
Output

1 2 3 4 5 6 7 8 9 10

Argumented Macros

 Used to define more complex and useful form of replacements in the


source program
 Syntax
#define identifier(v1 v2 v5…v8)

Example program to print square and cube values by using macro


substitution
#define sq(n) (n*n)
#define cube(n) (n*n*n)
#include<stdio.h>
main()
{
int a=5,b=3,s,c;
clrscr();
s=sq(a);
c=cube(b);
printf(“\nSquare value of 5 is %d”,s);
16GET26-C Programming I CSE

printf(“\nCube value of 3 is %d”,c);


}

Output

Square value of 5 is 25
Cube value of 3 is 27

Example program 2:

#define sq(n) (n*n)


#include<stdio.h>
main()
{
int a=3,s;
clrscr();
s=sq(a+2);
printf(“Output is %d”,s);
}
Output
Output is 11

Nested Macros
 Macros defined within another macros

Example
#define A 5
#define B A+2
16GET26-C Programming I CSE

Undefining a Macro
 A macro defiend with #define directive can be undefined with #undef
directive
 Syntax
#undef identifier_macro_template

 It is useful when we do not want to allow the use of macro in any


portion of the program

Example program to undefine a macro

#define wait getche()


void main()
{
int k;
#undef wait getche()
clrscr();
for (k=1;k<=5;k++)
pritnf(“%d\t”,k);
wait;
}
Output
Undefined symbol ‘wait’ in function

Conditional compilation in c

 Conditional compilation as the name implies code is compiled if certain


condition(s) hold true.

 Normally we use if keyword for checking some condition so we have to


use something different so that compiler can determine whether to
compile the code or not. The different thing is #if.

 Now consider the following code to quickly understand


 the scenario
16GET26-C Programming I CSE

Conditional Compilation (#if, #ifdef, #ifndef, #else, #elif, #endif, and


defined)

 Six directives are available to control conditional compilation. They


delimit blocks of program text that are compiled only if a specified
condition is true. These directives can be nested. The program text
within the blocks is arbitrary and may consist of preprocessor
directives, C statements, and so on. The beginning of the block of
program text is marked by one of three directives

#if
#ifdef
#ifndef
 Optionally, an alternative block of text can be set aside with one of two
directives

#else
#elif

 The end of the block or alternative block is marked by


the #endif directive.
16GET26-C Programming I CSE

 If the condition checked by #if , #ifdef , or #ifndef is true (nonzero),


then all lines between the matching #else (or #elif ) and
an #endif directive, if present, are ignored.
 If the condition is false (0), then the lines between the #if , #ifdef ,
or #ifndef and an #else , #elif , or #endif directive are ignored.

The defined Operator

 Another way to verify that a macro is defined is to use the defined unary
operator.
 The defined operator has one of the following forms

 defined name
 defined (name)

 An expression of this form evaluates to 1 if name is defined and to 0 if it


is not.
 The defined operator is especially useful for checking many macros with
just a single use of the #if directive.

 In this way, you can check for macro definitions in one concise line
without having to use many #ifdef or #ifndef directives.
 For example, consider the following macro checks
#ifdef macro1
printf( "Hello!\n" );
#endif
#ifndef macro2
printf( "Hello!\n" );
#endif
#ifdef macro3
printf( "Hello!\n" );
#endif

 Another use of the defined operator is in a single #if directive to


perform similar macro checks

#if defined (macro1) || !defined (macro2) || defined (macro3)


printf( "Hello!\n" );
#endif
16GET26-C Programming I CSE

#ifdef, #else and #endif

 "#ifdef" directive checks whether particular macro is defined or not.


 If it is defined, "If" clause statements are included in source file.
 Otherwise, "else" clause statements are included in source file for
compilation and execution.
#include<stdio.h>
#include<conio.h>
#define AGE 18
void main()
{
clrscr();
#ifdef AGE
{
printf("Eligible for voting\n"); Output
} Eligible for voting
#else
{
printf("Not eligible\n");
}
#endif
getch();
}
#if, #else and #endif

 "If" clause statement is included in source file if given condition is true.


 Otherwise, else clause statement is included in source file for
compilation and execution.

#include<stdio.h>
#include<conio.h>
#define AGE 18
void main() { Output
clrscr();
Eligible for voting
#if (AGE>=18)
{
printf("Eligible for voting");
16GET26-C Programming I CSE

}
#else
{
printf("\nNot eligible");
}
#endif
getch();
}
Undef

 This directive undefines existing macro in the program.


 In below program we first undefine age variable and again it define with
new value.

#include<stdio.h>
#include<conio.h>
#define age 18
void main()
{
clrscr();
printf("First defined value for age %d\n",age);
#undef age // undefining variable
#define age 30 // redefining age value for for new value
printf("Age after undef redefine %d",age);
getch();
}
Output

First defined value for age 18


Age after undef redefine 30
16GET26-C Programming I CSE

Pragma

 Pragma is used to call a function before and after main function in a C


program.

#include<stdio.h>
#include<conio.h>
#include<dos.h>
void function1( );
void function2( );
#pragma startup function1
#pragma exit function2
void main( )
{
delay(1000); printf ("\nI am main function" ) ; }
void function1( )
{
clrscr();
delay(500);
printf("\nI am function1");
}
void function2( )
{
delay(1000);
printf ( "\nI am function2" );
getch();
}
Output

I am function1 I am main function I am function2


Dr.Mahalingam College of Engineering and Technology
Department of Computer Science and Engineering
16GET14 – C PROGRAMMING
UNIT V FILES
Syllabus:

Introduction to Files, File access: Sequential access, Random access, File organization, File
operations (open, close, read, write, name) Command line arguments, Pre-processor directives,
Features, Macro expansion: File inclusion, Conditional compilation

Introduction to Files:

• Files are places where data can be stored permanently.

• Some programs expect the same set of data to be fed as input every time it is run.
– Cumbersome.
– Better if the data are kept in a file, and the program reads from the file.

• Programs generating large volumes of output.


– Difficult to view on the screen.
– Better to store them in a file for later viewing/ processing

• Definition of File: A collection of related information that is permanently stored on disk


and allows us to access and alter the information whenever necessary.

– A collection of records that can be accessed through a set of library functions


– A bunch of bytes stored on some storage device like magnetic disk (or) type

• Functions were used for reading and writing data


• File extensions- .exe, .com, .c, .cpp, .txt, .dat

Console oriented i/o:

• Terminals such as keyboard and screen is used


• Works with some major problems for large volumes of data

• Drawbacks

– Time consuming in handling large volumes of data


– The entire data will be lost when the program is terminated
– To overcome this a more flexible approach is used
– Data can be stored on the disk and read whenever necessary

Data file hierarchy:


– Bit : binary digits
– Byte: grouping of 8 bits
– Field: grouping of characters
– Record: grouping of data
– File: group of records
1
File streams

• Used to carry the communication between the program and output device (or) files and
program

• Stream : flow of data in bytes in sequence

– Source stream: if data is received from i/p devices in sequence


– Destination stream: when data is passed to o/p devices
– Input streams: brings data to the program
– Output stream: collects data from program

• Reading and writing of data is done with streams

• The type of the C data structure that represents a stream is called FILE rather than
“stream”. Sometimes the term file pointer is also used to mean “stream”

• The FILE type is declared in the header file stdio.h.

• A FILE object holds all of the internal state information about the connection to the
associated file, including such things as the file position indicator and buffering information.

Standard Streams

• Three predefined streams:

– stdin: The standard input stream, which is the normal source of input for the
program.
– stdout: The standard output stream, which is used for normal output from the
program.
– stderr: The standard error stream, which is used for error messages and diagnostics
issued by the program.

• Opening Streams:

Opening a file with the fopen function creates a new stream and establishes a connection
between the stream and a file. This may involve creating a new file.

FILE * fopen (const char *filename, const char *opentype)

If fopen is not able to open a file, it will return 0 (a NULL pointer). On success it will
return a file pointer as a handler.

• Closing Streams

– int fclose (FILE *stream)


– int fcloseall (void)

2
• fclose

This function causes stream to be closed and the connection to the corresponding file to be
broken. Any buffered output is written and any buffered input is discarded.

The fclose function returns a value of 0 if the file was closed successfully, and EOF if an error
was detected.

• fcloseall

This function causes all open streams of the process to be closed and the connections to
corresponding files to be broken.

File access: Sequential access, Random access

An access method is a program or a hardware mechanism that moves data between


the computer and an outlying device such as a hard disk (or other form of storage) or a display
terminal.

There are two types of access method random access and sequential access.

 A random-access data file enables to read or write information anywhere in the file. In a
sequential-access file, you can only read and write information sequentially, starting from
the beginning of the file.
 Comparison: If you are always accessing information in the same order, a sequential-
access file is faster. If you tend to access information randomly, random access is better.

Random access refers to the ability to


access data at random. The opposite of
random access is sequential access. To
go from point A to point Z in a
sequential-access system, you must pass
through all intervening points. In a
random-access system, you can jump
directly to point Z. Disks are random
access media, whereas tapes are
sequential access media.

Random access to files:

• Random access refers to the ability to access data at random

• Library functions used are:

– fseek()
– ftell()
– rewind()

3
fseek()

• Used to move the position of the file pointer to the desired location in the file

• Syntax: fseek(fptr,offset,position);

– fptr->file pointer

– offset-> - ve or +ve to reposition the file pointer towards the backward or forward
direction from the location specified by position

– position is the current location of the file pointer, takes one of three values

Integer value Macro name Location in the file


0 SEEK_SET Beginning of the file
1 SEEK_CUR Current position of file pointer
2 SEEK_END End of file

• Examples:

• fseek(fptr,n,0): moves n+1 bytes forward from the beginning of the file
• fseek(fptr,n,1): moves n+1 bytes forward from the current position
• fseek(fptr,-n,1): move n+1 bytes backward from current position
• fseek(fptr,-n,2): moves n+1 bytes backward from the end of the file
ftell()

– Used to get the current position of the file pointer

– Returns pointer from the beginning of the file, that is, a long int value

– If error occurs, returns -1

– Syntax: long int n=ftell(fp);

– i.e file pointer is at nth byte in the file

rewind()

– Used to bring the file pointer at the beginning of the file

– Syntax: rewind(fp);

4
File organization:

File I/O:
C provides a number of functions that helps to perform basic file operations. Following are the
functions,
Function Description

fopen() create a new file or open a existing file

fclose() closes a file

getc() reads a character from a file

putc() writes a character to a file

fscanf() reads a set of data from a file

fprintf() writes a set of data to a file

getw() reads a integer from a file

putw() writes a integer to a file

fseek() set the position to desire point

ftell() gives current position in the file

rewind() set the position to the begining point

feof () finds end of file.

• fprintf()
– used for writing characters ,strings, integers, float to files
– fscanf & fprintf similar to scanf & printf
– Difference - contains more parameter (file pointer- points to opened file)
– Syntax: fprintf(fp,”controlstring”,text);
• fscanf()
– Reads characters, strings,integers,float.etc from file pointed by file pointer
– Syntax: fscanf(fp,”control string”,text);
• getc()
– Reads a single character from the opened file and move the file pointer
– Returns EOF if end of file is reached
– Syntax:
char c;
c=getc(fp);
c-> a character is read from file whose pointer is fp
5
• putc()
– Used to write a single character into a file. If error occurs, returns EOF
– Syntax: putc(c,fp);
c is the character which is written in the file whose pointer is fp
• fgetc()
– Similar to get() function
– Reads a character and increments the file pointer
– If any error (or) EOF is reached, it returns EOF
– Syntax: c=fgetc(fp);
• fputc()
– Similar to put() function writes a character to file pointed by the file pointer
– Syntax: fputc(c,fp);
• fgets()
– Reads a string from a file pointed by file pointer
– Also copies the string to a memory location referenced by an array
• fputs()
– Used to write a string into the opened file
– Syntax fputs(text,fp);
– Text is a character string to be written onto the file pointed by fp
• putw()
– Used to write an integer value to a file pointed by file pointers
– Deals only with integer data
– Syntax: putw(v,fp);
v-int value
• getw()
– Returns the integer value from a file and increments the file pointer. Only integers
are allowed
– Syntax: v=getw(fp);

6
File Modes:
• Text mode
• Binary mode
1.Text mode:
 w: writing mode
- Opens a new file from the disk for writing
- If file already exists it overwrites
- When not found, new file is created
Syntax:
fp=fopen(“file.txt”,”w”);
 r: read mode
-Searches a file, if found loaded into memory for reading, if not found, returns NULL
-File pointer points to the beginning of the character file
fp=fopen(“file.txt”,”r”);
if(fp==NULL)
printf(“file not found”);
 a: append mode
-Opens a pre existing file for appending data
-Process starts at the end of the file i.e pointer points to the last
-If file not found, it will create a new file and will be opened.
-It returns NULL,if failed to open due to some other reasons
 w+ (write+read)
-Opens a text file for both reading and writing.
-Searches for the file,if found, contents are destroyed
-If not found, new file created
-If opening fails, returns NULL
fp=fopen(“data.txt”,”w+”);
 r+: read+write
-Used for both reading and writing
-If file does not exist,returns NULL
Syntax:
fp=fopen(“data.txt”,”r+”);
if(fp==NULL)
printf(“file not found..”);

7
 a+ : append+ read
Contents of the file can be read and records can be added at the end of the file
If file not found new file is created
If opening operation failed- NULL
Syntax:
fp=fopen(“data.txt”,”a+”);

Difference between Append and Write Mode


In both the modes, new file is created if it doesn't exist already. When opening a file in the write
mode, the file is reset, resulting in deletion of any data already present in the file. Append mode is
used to append or add data to the existing data of file(if any). Hence, in Append(a) mode, the cursor
is positioned at the end of the present data in the file.
2.Binary mode
When numerical data is to be transferred to disk from RAM, data occupies more
memory space on disk. To overcome this, a file can be opened in binary mode, which takes lesser
memory than text mode.
Mode Description
wb Write binary
Opens binary file in write mode
rb Read binary
ab Append binary
r+b Read+write of binary file
w+b Write+read of binary file
a+b Append+write
Note: All operations are exactly same as text mode, only differ in file type i.e it involves binary file
Functions used to read and write in binary mode: fread() and fwrite()
Syntax:
size_t fread(void *ptr, size_t size, size_t nmemb, FILE *stream);
size_t fwrite(const void *ptr, size_t size, size_t nmemb, FILE *stream);
The first argument is a pointer to buffer used for reading/writing the data. The data read/written is
in the form of ‘nmemb’ elements each ‘size’ bytes long.

8
File operations:
1.Opening a file:
The fopen() function is used to create a new file or to open an existing file.
Syntax :
*fp = FILE *fopen(const char *filename, const char *mode);
Here filename is the name of the file to be opened and mode specifies the purpose of opening the
file. *fp is the FILE pointer (FILE *fp), which will hold the reference to the opened(or created) file.

2.Reading and writing in a file:


• The simplest file input-output (I/O) function are getc and putc.
• getc is used to read a character from a file and return it.
char ch = getc (fp) ;
– getc will return an end-of-file marker EOF, when the end of the file has been
reached.
• putc is used to write a character to a file.
putc (c, fp) ;
Example program for read and write operations on file:
#include<stdio.h>
#include<conio.h>
main()
{
FILE *fp;
char ch;
fp = fopen("one.txt", "w");
printf("Enter data");
while( (ch = getchar()) != EOF) {
putc(ch,fp);
}
fclose(fp);
fp = fopen("one.txt", "r");

while( (ch = getc(fp)! = EOF)


printf("%c",ch);
fclose(fp);
}
• file versions of scanf and printf, called fscanf and fprintf can also be used.
• General format:
fscanf (file_pointer, control_string, list) ;
fprintf (file_pointer, control_string, list) ;

9
• Examples:
fscanf (fp, “%d %s %f”, &roll, dept_code, &cgpa) ;
fprintf (out, “\nThe result is: %d”, xyz) ;

3.Closing a file:
• The file that is opened must be closed after the work is done
• The fclose() function is used to close an already opened file.
• Syntax
int fclose( FILE *fp );
 Here fclose() function closes the file and returns zero on success, or EOF if there is an error
in closing the file. This EOF is a constant defined in the header file stdio.h.
 fclose()-function closes one file at a time
 fcloseall()-closes all the opened files and returns the no of files closed- no arguments
required

Programs:

1. Perform various File operations


Program:
#include<stdio.h>
#include<conio.h>
void main()
{
FILE *fp;
char c;
clrscr();
fp=fopen("input.txt","r");
if(fp!=NULL)
printf("File opened in read mode");
printf("\nReading from file:\n");
while(!feof(fp))
{
c=fgetc(fp);
printf("%c",c);
}
fclose(fp);
fp=fopen("input.txt","a");
if(fp==NULL)
{
printf("File cant be opened");
exit(1);
10
}
else
printf("\nFile opened in write mode");
printf("\nEnter the string to append");
while(c!='.')
{
c=getche();
fputc(c,fp);
}
fclose(fp);
printf("\nContents after appending:\n");
fp=fopen("input.txt","r");
while(!feof(fp))
{
c=fgetc(fp);
printf("%c",c);
}
fclose(fp);
printf("File closed");
getch();
}

Output:

11
2. Write a Sentence to a File

Program:
#include<stdio.h>
#include<conio.h>
void main()
{
FILE *fp;
char c;
clrscr();
fp=fopen("new1.txt","a");
if(fp!=NULL)
printf("File opened in write mode");
printf("\nEnter the string to write\n");
while(c!='.')
{
c=getche();
fputc(c,fp);
}
fclose(fp);
printf("\nContents after writing:\n");
fp=fopen("new1.txt","r");
while(!feof(fp))
{
c=fgetc(fp);
printf("%c",c);
}
fclose(fp);
printf("\nFile closed");
getch();
}

Output:

12
3. Read a Line From a File and Display it

Program:
#include<stdio.h>
#include<conio.h>
void main()
{
FILE *fp;
char c;
clrscr();
fp=fopen("new1.txt","r");
if(fp!=NULL)
printf("File opened in read mode");
printf("\nReading from file:\n");
while(!feof(fp))
{
c=fgetc(fp);
printf("%c",c);
}
fclose(fp);
printf("\nFile closed");
getch();
}

Output:

13
4. Copy the contents of one file into another

Program:
#include<stdio.h>
#include<conio.h>
void main() {
FILE *fp1, *fp2;
char a;
clrscr();
fp1 = fopen("new1.txt", "r");
if (fp1 == NULL) {
puts("cannot open this file");
exit(1);
}
printf("Source file opened in read mode\n");
fp2 = fopen("test1.txt", "w");
if (fp2 == NULL) {
puts("Not able to open this file");
fclose(fp1);
exit(1);
}
printf("Destination file opened in write mode\n");
do {
a = fgetc(fp1);
fputc(a, fp2);
} while (a != EOF);
printf("Data copied\n");
fcloseall();
getch();
}
Output:

Contents of destination file:


Welcome to C programming. This program copies contents from one file to another.

14
5. Display source program as Output

Program:
#include<stdio.h>
#include<conio.h>
void main()
{
FILE *fp;
char c;
clrscr();
fp=fopen("file1.c","r");
if(fp!=NULL)
printf("Source File opened in read mode");
printf("\nReading from file:\n");
while(!feof(fp))
{
c=fgetc(fp);
printf("%c",c);
}
fclose(fp);
printf("\nFile closed");
getch();
}

Output:

15
Command Line Arguments

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

They are handled using two commands: argc and argv[]

where argc refers to the number of arguments passed including program name, and argv[]
is a pointer array which points to each argument passed to the program.

Properties of Command Line Arguments:

 They are passed to main() function.


 They are parameters/arguments supplied to the program when it is invoked.
 They are used to control program from outside instead of hard coding those values inside
the code.
 argv[argc] is a NULL pointer.
 argv[0] holds the name of the program.
 argv[1] points to the first command line argument and argv[n] points last argument.

Example for Command Line Argument:

#include <stdio.h>
#include <conio.h>
void main( int argc, char *argv[] )
{
int i;
if( argc >= 2 )
{
printf("The arguments supplied are:\n");
for(i=1;i< argc;i++)
{
printf("%s\t",argv[i]);
}
}
else
{
printf("argument list is empty.\n");
}
getch();
}
Output:
C:\turboc> filename.exe welcome to programming
The arguments supplied are:
welcome to programming

16
Another Example:
#include<stdio.h>
void main( int argc, char *argv[])
{
if(argc>1)
printf(“welcome %s”,argv[1]);
else
printf(“you must type name”);
}
Output:
C:\turboc> filename.exe india
welcome india

17

You might also like