1. ECE & EEE | I YEAR | II SEMESTER B1360 | COMPUTER PROGRAMMING | UNIT 5
1 |Prepared By : Mr. PRABU.U/AP |Dept. of Computer Science and Engineering | SKCET |
UNIT V
Files – Operations on a file – Random access to files – command line arguments.
Introduction to preprocessor – Macro substitution directives – File inclusion directives–
conditional compilation directives – Miscellaneous directives.
5.1 FILES
“A file is a collection of related information that is permanently stored on the
disk and allows us to access and alter the information whenever necessary.”
Group of related record form a FILE. FILE is a place on the disk where group of
related data is stored. DATA FILE is used to store information in floppy disk, hard disk.
Field is a data item used to store a single unit. Group of related field constitute a
RECORD. FILE is classified into three types. They are
Numeric file
It contains numeric data.
Text file
It consists of text data.
Data files
It consists of data grouped in the form of structure. It may have text, numeric
data or both.
FILE OPERATION LEVELS
There are two FILE operation levels. They are
Low level Input/Output operations
It uses system calls.
High level Input/Output operations
It uses functions in standard C Input Output Library.
Function Name Operations
fopen() Creates a new file for use. Opens an existing file for use.
fclose() Closes a file which has been opened for use.
2. ECE & EEE | I YEAR | II SEMESTER B1360 | COMPUTER PROGRAMMING | UNIT 5
2 |Prepared By : Mr. PRABU.U/AP |Dept. of Computer Science and Engineering | SKCET |
fgetc() Reads a character from a file.
fputc() Writes a character to the file.
fprintf() Writes set of data values to a file.
fscanf() Reads a set of data values from a file.
getw() Reads an integer from a file.
putw() Writes an integer to a file.
fseek() Sets the position to desired position in the file.
ftell() Gives the current position in the file.
rewind() Sets the position to the beginning of the file
fgets() Reads a string from the file
fputs() Writes a string to the file.
fread() Reads unformatted data from the file
fwrite() Writes unformatted data to the file
To store data in a file Secondary Memory is used. When a file is retrieved from an
Operating System OS specifies the filename, Data structures and Purpose.
Here File name is a string of characters. It contains two parts. First one is
Primary name and then the other is optional period with extension.
FILE data type
FILE is a structure data type. It is used to establish file buffer area.
To get buffer area the syntax is
FILE *fp;
where fp is a file pointer or stream pointer. fp contains all the information about file. It
serves as link between system and program. FILE is a keyword. It refers to the file
control structure for streams.
Opening a file
“fopen” function is used to open a stream or data file. File should be opened
before reading or writing from it. If a file is opened ‘fopen’ functions returns FILE
pointer to the beginning of buffer area. If file is not opened NULL value is returned.
The Syntax of fopen is
FILE *fopen(“filename”,“mode”);
3. ECE & EEE | I YEAR | II SEMESTER B1360 | COMPUTER PROGRAMMING | UNIT 5
3 |Prepared By : Mr. PRABU.U/AP |Dept. of Computer Science and Engineering | SKCET |
fopen() function returns pointer to structure associated with the file. fopen()
function needs two arguments of type string. First argument filename refers to the
name of file which is to be opened. Second argument mode refers to file mode.
File
Type
Modes of File Operations
“r” Opens existing file for reading. If file does not exist error occurs.
“w” Opens new file for writing. If the file exists contents of the file are
overwritten.
“a” Opens existing file for appending. New information are added at
the end of file. Old Contents are not overwritten but added to the
end of the file. if the name of the file specified does not exist new
file is created.
“rb” Opens a binary file for reading.
“wb” Creates and opens new binary file for writing. If the file specified
exists contents of the file are overwritten.
“a+” Opens existing file for reading and writing.
“r+b” or
“rb+”
Opens a binary file for read and write operations.
“w+b” or
“wb+”
Creates and opens binary file for read and write operations.
“a+b” or
“ab+”
Opens a binary file for for read and write operations.
Closing a file
File is closed when all input output operations are completed. fclose() function is
used to close opended file. This function makes all buffers associated with the file empty
and all links to the file broken. Whenever we want to reopen the same file we have to
close all other file. The syntax for closing a file is
fclose(fp);
4. ECE & EEE | I YEAR | II SEMESTER B1360 | COMPUTER PROGRAMMING | UNIT 5
4 |Prepared By : Mr. PRABU.U/AP |Dept. of Computer Science and Engineering | SKCET |
#include< stdio.h >
void main()
{
file *f1;
clrscr();
printf(“Data input output”);
f1=fopen(“Input”,”w”); /*Open the file Input*/
while((c=getchar())!=EOF) /*get a character from key board*/
putc(c,f1); /*write a character to input*/
fclose(f1); /*close the file input*/
printf(“nData outputn”);
f1=fopen(“INPUT”,”r”); /*Reopen the file input*/
while((c=getc(f1))!=EOF)
printf(“%c”,c);
fclose(f1);
}
5.2 OPERATIONS ON FILES
There are eight operations on files. They are
putc()
getc()
getw()
putw()
fscanf()
fread()
fprintf()
fwrite()
putc()
This function operates on file that is copied in writing mode. The syntax for
putc() is
int putc(int ch, FILE *fp);
getc()
This function operates on file that is opened in reading mode. The syntax for
getc() is
int getc(FILE *fp);
Reads character from file pointed by file pointer fp and displays on it screen.
Now file pointer moves by one character position for every getc() function and returns
EOF (end-of-file). EOF is a constant that indicates the end-of-file reached on a file. To
get character from a file terminating character(^z) is entered.
5. ECE & EEE | I YEAR | II SEMESTER B1360 | COMPUTER PROGRAMMING | UNIT 5
5 |Prepared By : Mr. PRABU.U/AP |Dept. of Computer Science and Engineering | SKCET |
getw()
Reads an integer value from file pointed by file pointer. The syntax for getw() is
int getw(FILE *fp);
Returns next integer from input output stream.
/*Example program for using getw and putw functions*/
#include< stdio.h >
void main()
{
FILE *f1,*f2,*f3;
int number i;
printf(“Contents of the data filenn”);
f1=fopen(“DATA”,”W”);
for(i=1;i< 30;i++)
{
scanf(“%d”,&number);
if(number==-1)
break;
putw(number,f1);
}
fclose(f1);
f1=fopen(“DATA”,”r”);
f2=fopen(“ODD”,”w”);
f3=fopen(“EVEN”,”w”);
while((number=getw(f1))!=EOF) /* Read from data file*/
{
if(number%2==0)
putw(number,f3); /*Write to even file*/
else
putw(number,f2); /*write to odd file*/
}
fclose(f1);
fclose(f2);
fclose(f3);
f2=fopen(“ODD”,”r”);
f3=fopen(“EVEN”,”r”);
printf(“nnContents of the odd filenn”);
while(number=getw(f2))!=EOF)
printf(“%d”,number);
printf(“nnContents of the even file”);
while(number=getw(f3))!=EOF)
printf(“%d”,number);
fclose(f2);
fclose(f3);
getch();
}
6. ECE & EEE | I YEAR | II SEMESTER B1360 | COMPUTER PROGRAMMING | UNIT 5
6 |Prepared By : Mr. PRABU.U/AP |Dept. of Computer Science and Engineering | SKCET |
putw()
This function is used to write integer value on file pointed by file pointer. The
syntax for putw() is
int putw(int w, FILE *fp);
Here fp is a file pointer and w is an integer variable.
fscanf()
The syntax for fscanf() is
int fscanf(FILE *fp, format-specification, list of variables);
/*Program to handle mixed data types*/
#include< stdio.h >
main()
{
FILE *fp;
int num,qty,i;
float price,value;
char item[10],filename[10];
printf(“Input filename”);
scanf(“%s”,filename);
fp=fopen(filename,”w”);
printf(“Input inventory datann”0;
printf(“Item namem number price quantityn”);
for(i=1;i< =3;i++)
{
fscanf(stdin,”%s%d%f%d”,item,&number,&price,&quality);
fprintf(fp,”%s%d%f%d”,itemnumber,price,quality);
}
fclose (fp);
fprintf(stdout,”nn”);
fp=fopen(filename,”r”);
printf(“Item name number price quantity value”);
for(i=1;i< =3;i++)
{
fscanf(fp,”%s%d%f%d”,item,&number,&prince,&quality);
value=price*quantity”);
fprintf(“stdout,”%s%d%f%d%dn”,item,number,price,quantity,value);
}
fclose(fp);
}
7. ECE & EEE | I YEAR | II SEMESTER B1360 | COMPUTER PROGRAMMING | UNIT 5
7 |Prepared By : Mr. PRABU.U/AP |Dept. of Computer Science and Engineering | SKCET |
fread()
This function reads data from stream of any data type. The syntax for fread() is
size_t fread(void *ptr, size_t size,size_t n, FILE *fp);
size_t used for memory objects and repeats count.
fprintf()
This function is used to work with file. The syntax for fprintf() is
int fprintf(FILe *fp, format specification, list of variables);
where fp is a file pointer. Format specification specifies the format for output variables
to be stored. List of variables are those variables written to file pointed by fp.
fwrite()
This function writes to a stream or specified file. The syntax for fwrite() is
size_t fwrite(const void *ptr,size_t size,size_t n,FILE *fp);
where n is the number of elements written to that file.
5.3 RANDOM ACCESS TO FILE IN C
Random access means we can move to any part of a file and read or write data
from it without having to read through the entire file. we can access the data stored in
the file in two ways.
1.Sequentially
2.Randomly
Some points about Sequentially and Randomly accessing of Files
If we want to access the forty fourth record then first forty three record read
sequentially to reach forty four record
In Random access data can be accessed and processed directly
If there is no need to read each record sequentially then use Randomly access
If we want to access a particular record random access takes less time than the
Sequential access
C supports these function for random access file.
1. fseek( ) Function
2. ftell ( ) Function
1. fseek( ) Function
This function is used for setting the file position pointer at the specified bytes .
fseek is a function belonging to the ANCI C standard Library and included in the file
<stdio.h>. Its purpose is to change the file position indicator for the specified stream.
int fseek(FILE *stream_pointer, long offset, int origin);
8. ECE & EEE | I YEAR | II SEMESTER B1360 | COMPUTER PROGRAMMING | UNIT 5
8 |Prepared By : Mr. PRABU.U/AP |Dept. of Computer Science and Engineering | SKCET |
Argument meaning
stream_pointer is a pointer to the stream FILE structure of which the position indicator
should be changed;
offset is a long integer which specifies the number of bytes from origin where the
position indicator should be placed;
origin is an integer which specifies the origin position. It can be:
SEEK_SET: origin is the start of the stream
SEEK_CUR: origin is the current position
SEEK_END: origin is the end of the stream
/* * Program to understand the use of fseek function */
#include<stdio.h>
#include<conio.h>
#include<stdlib.h>
struct emprecord
{
char name[30];
int age;
float sal;
}emp;
void main()
{
int n;
FILE *fp;
fp=fopen("employee.dat","rb");
if (fp==NULL)
{
printf("/n error in opening file");
exit(1);
}
printf("enter the record no to be read");
scanf("%d",&n);
fseek(fp,(n-1)*sizeof(emp),0);
fread(&emp,sizeof(emp),1,fp);
printf("%st,emp.name);
printf("%dt",emp.age);
printf("%fn",emp.sal);
fclose(fp);
getch();
};
This function return the current position of the file position pointer. The value is
counted from the beginning of the file.
/** program to understand the use of ftell()*/
#include<stdio.h>
#include<conio.h>
#include<stdlib.h>
9. ECE & EEE | I YEAR | II SEMESTER B1360 | COMPUTER PROGRAMMING | UNIT 5
9 |Prepared By : Mr. PRABU.U/AP |Dept. of Computer Science and Engineering | SKCET |
struct emprecord
{
char name[30];
int age;
float sal;
}emp;
void main()
{
FILE *fp;
fp=fopen("employee.dat","rb");
if (fp==NULL)
{[an error occurred while processing this directive]
printf("/n error in opening file");
exit(1);
}
printf("position pointer in the beginning -> %1d ",ftell(fp));
while("fread(position pointer -> 1%dn",ftell(fp));
printf("position pointer -> %1dn",ftell(fp));
printf("%st",emp.name);
printf("%dt",emp.age);
printf("%f",emp.sal);
}
printf("size of the file in bytes is %1dn",ftell(fp));
fclose(fp);
getch();
};
5.4 COMMAND LINE ARGUMENTS
Command line argument is a parameter supplied to a program when the
program is invoked. This parameter represents filename of the program that should
process.
In general, execution of C program starts from main() function. It has two
arguments like argc and argv.
The argc is an argument counter that counts the number of arguments on the
command line.
The argv is an argument vector. It represents an array of character pointer that
point to command line arguments.
The size of the array will be equal to the value of argc. Information contained in
command line is passed to program through these arguments whenever main is called.
The first parameter in command line is program name.
#include<stdio.h>
#include<stdlib.h>
void main(int argc , char *argv[])
{
int i,sum=0;
if(argc<3)
{
printf("you have forgot to type numbers.");
10. ECE & EEE | I YEAR | II SEMESTER B1360 | COMPUTER PROGRAMMING | UNIT 5
10 |Prepared By : Mr. PRABU.U/AP |Dept. of Computer Science and Engineering | SKCET |
exit(1);
}
printf("The sum is : ");
for(i=1;i<argc;i++)
sum = sum + atoi(argv[i]);
printf("%d",sum);
}
The C library function int atoi(const char *str) converts the string argument str to an
integer (type int).
5.5 INTRODUCTION TO PREPROCESSOR
PREPROCESSOR
Preprocessor is a program that process source program before it passes through
the compiler. Preprocessor is system software that consists of special statements called
directives. It operates under the control of directives known as preprocessor command
lines. Preprocessor directives are placed in the source program before the main line.
Whenever a C program is compiled, source program runs through preprocessor.
Preprocessor
Executed at the beginning of compilation process.
Do not change Original C program but creates new file. The new file is the
processed version of program.
Appear in the beginning of C program.
It can be included in any part of a program. If it appear in the middle then the
directive is applied to portion of program.
Preprocessor symbol should not be enclosed within quotes and should not be
enclosed with semicolon.
#define directive increases the readability of the C program. It is used to create
function like macros.
Rules for defining preprocessor
All preprocessor directives begin with sharp sign. i.e.,(#)
It starts in first column.
It should not terminate with semicolon.
It may appear at any place in the source file. i.e., Outside the function, inside the
function or inside compound statements.
Preprocessor directives begin with the symbol #.
It does not require semicolon at the end.
PREPROCESSOR DIRECTIVES
Directive Function
#define Define macro substitution.
#undef Undefines a macro.
#include Specifies the file to be included.
#ifdef Test a macro definition.
#endif Specifies the end of #if
#ifndef Tests whether a macro is not defined
#if Test a compile time condition.
11. ECE & EEE | I YEAR | II SEMESTER B1360 | COMPUTER PROGRAMMING | UNIT 5
11 |Prepared By : Mr. PRABU.U/AP |Dept. of Computer Science and Engineering | SKCET |
#else Specify alternatives when #if test fails
TYPES OF PREPROCESSOR DIRECTIVES
The types of preprocessor directives are
File Inclusion
Macro Definition
Conditional Compilation
File Inclusion Directives
It is the first type. This directive is used for including one or more files in the
program. It instructs the compiler to make a copy of specified file to be included in place
of the directive. The general form is
#include<filename> - It make preprocessor to look for file with specified filename in
special directories set aside for files.
#include“filename” - It preprocessor to look for file with specified filename in
Current working directory.
Macro Substitution Directives
Macro definition is the second type of preprocessor directives. The #define
directive is used here. It is also used to define symbolic constant and assign value. The
general form is
#define identifier set-of-characters
where identifier also known as “macro name” or “macro template”.
#define FIVE 5
#define SIX FIVE+1
#define SEVEN SIX+1
#include<stdio.h>
#include<conio.h>
{
clrscr();
printf(“%d t %d t %d”,FIVE,SIX,SEVEN);
getch();
}
CONDITIONAL COMPILATION
Directives permit certain segment of source code to be selectively compiled.
Directives are also called as Conditional Compilation. The Conditional directives are
#if
#else
#elif
#endif
#ifdef
#ifndef
Format of #if and #endif directive
The format of #if and #endif directive is
#if constant expression
sequence of statements
12. ECE & EEE | I YEAR | II SEMESTER B1360 | COMPUTER PROGRAMMING | UNIT 5
12 |Prepared By : Mr. PRABU.U/AP |Dept. of Computer Science and Engineering | SKCET |
#endif
If the value of constant expression is true sequence of statements are executed. if the
expression value is false compiler skip the statements.
Format of #if and #else directive
#else statement helps to terminate #if statement. If the given constant or
expression is false #else block is executed. The general form is
#if constant expression
Sequence of statements
#else
Sequence of statements
#endif
Here for nested if statements #elif directives can be used. The general format of #elif is
#if constant expression1
statements
#elif constant expression2
sttements
……………
#endif
Here if expression1 is true it is executed and all other expressions are skipped.
#ifdef directive is used for conditional compilation. The general form is
#ifdef macroname
statements
#endif
#include directive
#include directive has two forms. They are
1. #include<filename>
This directive instruct compiler to search for file in the directory that contains
header file.
Eg: #include<stdio.h>
#include<conio.h>
2. #include“filename”
This instruct compiler to search for file in the current directory.
Eg: #include“stdio.h”
#include“conio.h”
#define A “X is Big”
#define B “Y is Big”
#include<stdio.h>
{
int X,Y;
printf(“n Enter value for X and Y : “);
scanf(“%d%d”,&x,&y);
if(X>Y)
13. ECE & EEE | I YEAR | II SEMESTER B1360 | COMPUTER PROGRAMMING | UNIT 5
13 |Prepared By : Mr. PRABU.U/AP |Dept. of Computer Science and Engineering | SKCET |
printf(A);
else
printf(B);
getch();
}
MISCELLANEOUS DIRECTIVES
#pragma
#error
#line
#pragma
The 'pragma' directive is the method specified by the C standard for providing
additional information to the compiler.
#pragma startup and #pragma exit
These directives allow us to specify functions that are called upon program
startup (before main()) or program exit (just before the program terminates). Their
usage is as follows
void fun1();
void fun2();
#pragma startup fun1
#pragma exit fun2
main()
{
printf("Inside main");
}
void fun1()
{
printf("Inside fun1");
}
void fun2()
{
printf("Inside fun2");
}
#pragma warn
#pragma warn
#pragma warn -rv1 /* return value */
#pragma warn -par /* parameter not used */
#pragma warn -rch /* unreachable code */
int f1()
{
int a=5;
}
void f2(int x)
{
14. ECE & EEE | I YEAR | II SEMESTER B1360 | COMPUTER PROGRAMMING | UNIT 5
14 |Prepared By : Mr. PRABU.U/AP |Dept. of Computer Science and Engineering | SKCET |
printf("Inside f2");
}
int f3()
{
int x=6;
return x;
x++;
}
void main()
{
f1();
f2(7);
f3();
}
MEMORY FUNCTIONS
malloc
Used to allocate contiguous block of memory in bytes.
Allocates memory size in bytes. If memory allocated success it returns
starting address else returns NULL.
Returns starting address of memory through pointer variable of type cat-
type.
Memory space is not initialized.
The general form of malloc function is
pointer variable=(cast-type *)malloc(size);
where pointer variable is a valid variable. cast-type is type of pointer returned by
malloc() such as int, char, etc,. size is required size of memory in bytes.
#include<stdio.h>
#include<alloc.h>
void main()
{
int *a; int i,n,sum=0;
printf(“Enter size of array :”);
scanf(“%d”,&n);
a=(int *)malloc(sizeof(int)*n); // ( Or ) a=malloc(sizeof(int)*n);
if(a!=NULL)
{
printf(“Enter %d elements :”,n);
for(i=0;i<n;i++)
{
scanf(“%d”,&a[i]);
sum=sum+a[i];
}
15. ECE & EEE | I YEAR | II SEMESTER B1360 | COMPUTER PROGRAMMING | UNIT 5
15 |Prepared By : Mr. PRABU.U/AP |Dept. of Computer Science and Engineering | SKCET |
printf(“Sum of given integers is %d”,sum);
}
else
printf(“Memory cannot be allocated”);
}
calloc() function
Used to allocate multiple blocks of contiguous memory in bytes.
All blocks are of same size. If memory allocated success it returns starting
address else returns NULL.
Allocates n blocks of memory space of size in bytes and returns starting
address of memory through pointer variable of type cast-type.
Allocated memory space is filled with zeros if memory is initialized.
The general form of calloc function is
pointer variable=(cast-type *)calloc(n,size);
where pointer variable is a valid variable. cast-type is type of pointer returned by
calloc() such as int, char, etc,. n is the number of blocks and size is required size of
memory in bytes.
#include<stdio.h>
#include<alloc.h>
void main()
{
int *ptr; int i,n;
printf(“Enter size of array :”);
scanf(“%d”,&n);
ptr=(float *)calloc(n,sizeof(float));
// ( Or ) ptr=calloc(n,sizeof(float));
if(ptr==NULL)
{
printf(“Memory cannot be allocated”);
exit(0);
}
printf(“Value in the allocated memory area”);
for(i=0;i<n;i++)
printf(“n ptr[%d] = %5.2f”,i,ptr[i]);
}
Output:
Enter size of array : 5
Enter 5 elements : 8 8 8 8 8
Sum of given integers is 40
Enter size of array : 0
Memory cannot be allocated
16. ECE & EEE | I YEAR | II SEMESTER B1360 | COMPUTER PROGRAMMING | UNIT 5
16 |Prepared By : Mr. PRABU.U/AP |Dept. of Computer Science and Engineering | SKCET |
realloc() function
Used to increase or decrease size of memory previously allocated.
All blocks are of same size. If memory allocated success it returns address of
new area through pointer variable else returns NULL.
Original block of data is lost or freed.
Allocates n blocks of memory space of size in bytes and returns starting
address of memory through pointer variable of type cast-type.
Allocated memory space is filled with zeros if memory is initialized.
The general form of realloc function is
r=realloc(old_ptr,new_size);
where r is valid C variable already defined. old_ptr is the pointer variable used in
malloc() or calloc() function. new_size is the size of new memory needed.
#include<stdio.h>
#include<alloc.h>
void main()
{
int *marks,i,n=0,add1,sum=0;
char ch;
printf(“Enter Number of subject for calculating total mark :”);
scanf(“%d”,&n);
printf(“Enter marks for %d subjects: ”,n);
marks=malloc(sizeof(int) *n);
for(i=0;i<n;i++)
{
scanf(“%d”,&marks[i]);
sum=sum+marks[i];
}
for(i=0;i<n;i++)
printf(“n Subject %d mark = %d”,i+1,marks[i]);
printf(“n Total marks of %d subjects are %d”,n,sum);
printf(“n Do u want to add some more subjects to the Previous list y/n:”);
if((ch=getche())!=’n’)
{
printf(“n Enter the additional number of subjects :”);
scanf(“%d”,&add1);
Output:
Enter size of array : 3
Value in the allocated memory area
ptr[0] = 0.00
ptr[1] = 0.00
ptr[2] = 0.00
Enter size of array : 0
Memory cannot be allocated
17. ECE & EEE | I YEAR | II SEMESTER B1360 | COMPUTER PROGRAMMING | UNIT 5
17 |Prepared By : Mr. PRABU.U/AP |Dept. of Computer Science and Engineering | SKCET |
marks=realloc(marks,n *sizeof(int));
printf(“n Enter marks for additional %d subjects :”,add1);
for(i=0;i<add1;i++)
{
scanf(“%d”,&marks[n+i]);
sum=sum+marks[n+i];
}
n=n+add1;
}
for(i=0;i<n;i++)
printf(“n Subject %d mark = %df”,i+1,marks[i]);
printf(“n Total marks of %d subjects are %d”,n,sum);
free(marks);
}
Output
Enter Number of subject for calculating total mark : 3
Enter marks for 3 subjects: 85 78 93
Subject 1 mark = 85
Subject 2 mark = 78
Subject 3 mark = 93
Total marks of 3 subjects are 256
Do u want to add some more subjects to the Previous list y/n: y
Enter the additional number of subjects: 2
Enter marks for additional 2 subjects: 100 68
Subject 1 mark = 85
Subject 2 mark = 78
Subject 3 mark = 93
Subject 4 mark = 100
Subject 5 mark = 68
Total marks of 5 subjects are 424
free() function
Used to free (release or deallocate) block of unused / used memory. The general
form of realloc function is
free(pointer_variable);
where pointer_variable is a pointer to memory block which has been already created by
malloc() or calloc() function.