Unit 5 PWC
Unit 5 PWC
Example:
#include<stdio.h>
#define PI 3.14
void main()
{
printf("%f",PI);
}
Output
3.14
Miscellaneous directive.
example #error, #line
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
Syntax
Simple Macros
Argumented Macros
Nested Macros
Simple Macros
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
1 2 3 4 5 6 7 8 9 10
Argumented Macros
Output
Square value of 5 is 25
Cube value of 3 is 27
Example program 2:
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
Conditional compilation in c
#if
#ifdef
#ifndef
Optionally, an alternative block of text can be set aside with one of two
directives
#else
#elif
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)
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
#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
#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
Pragma
#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
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:
• 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.
• Drawbacks
• Used to carry the communication between the program and output device (or) files and
program
• 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”
• 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
– 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.
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
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.
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.
– 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
• 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()
– Returns pointer from the beginning of the file, that is, a long int value
rewind()
– 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
• 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+”);
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.
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:
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:
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.
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.
#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