UNIT V 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 FILE 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. C supports a number of functions that have the ability to perform basic file operations, which include: 1. Naming a file 2. Opening a file 3. Reading from a file 194
This document is posted to help you gain knowledge. Please leave a comment to let me know what you think about it! Share it to your friends and learn new things together.
Transcript
UNIT V
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 FILE
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.C supports a number of functions that have the ability to perform basic file operations, which include:
1. Naming a file 2. Opening a file 3. Reading from a file 4. Writing data into a file 5. Closing a file
FILE OPERATION LEVELS There are two FILE operation levels. They are
1. Low level Input/Output operations It uses system calls.
2. High level Input/Output operations It uses functions in standard C Input Output Library.
194
UNIT V
File operation functions in C:
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’
195
UNIT V
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”); 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.
196
UNIT V
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);
#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 output\n”); f1=fopen(“INPUT”,”r”); /*Reopen the file input*/ while((c=getc(f1))!=EOF) printf(“%c”,c); fclose(f1); } The program shown below displays use of a file operations. The data enter through the keyboard and the program writes it. Character by character, to the file input. The end of the data is indicated by entering an EOF character, which is control-z. the file input is closed at this signal. OUTPUTData input outputAll cse students are bright students^Z
Data output
All cse students are bright students
197
UNIT V
Operations on Files There are eight operations on files. They are
putc() This function operates on file that is copied in writing mode. The syntax for putc() is
putc(int ch, FILE *fp); getc() This function operates on file that is opened in reading mode. The syntax for getc() is
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.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>main(){FILE *f1,*f2,*f3;int number,I;printf(“Text inside the data file\n\n”);f1=fopen(“DATA”,”W”);for(I=1;I< 30;I++){scanf(“%d”,&number);if(number==-1)
198
UNIT V
break;putw(number,f1);}fclose(f1);f1=fopen(“DATA”,”r”);f2=fopen(“ODD”,”w”);f3=fopen(“EVEN”,”w”);while((number=getw(f1))!=EOF)/* Reading data from the file*/{if(number%2==0)putw(number,f3);/*Write to even Numbers file*/elseputw(number,f2);/*write to odd Numbers file*/}fclose(f1);fclose(f2);fclose(f3);f2=fopen(“ODD”,”r”);f3=fopen(“EVEN”,”r”);printf(“\n\nData From the odd file\n\n”);while(number=getw(f2))!=EOF)printf(“%d”,number);printf(“\n\nData from the even file”);while(number=getw(f3))!=EOF)printf(“%d”,number);fclose(f2);fclose(f3);} OUTPUTContents of the data file12131415-1
Contents of the odd file
13
15
Contents of the even file
12
199
UNIT V
14
putw()
This function is used to write integer value on file pointed by file pointer. The syntax for putw() is
putw(int w, FILE *fp);
Here fp is a file pointer and w is an integer variable.
fscanf()
The syntax for fscanf() is
fscanf(FILE *fp, format-specification, list of variables);
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.
Item name Number Price Quantityfan 12 2400 12light 23 100 10switch 12 20 100
Item name Number Price Quantity Valuefan 12 2400.00 100 240000.0012light 23 100.00 100 10000.0010switch 12 20.00 100 2000.00fread() 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. fwrite() This function writes to a stream or specified file. The syntax for fwrite() is
where n is the number of elements written to that file.Example for fread and fwrite#include <stdio.h>#define NELEM 3int main(void){ FILE *fp; struct product { int cat_num; float cost; }; typedef struct product product; product productarr[NELEM] = {{2,20.1},{4,40.1},{6,60.1}}; product one_product, *product_ptr = &one_product; int i, irc; fp = fopen("c11-struct-file","w+"); if (fp != NULL); irc = fwrite(productarr, sizeof(product), NELEM, fp); printf(" fwrite return code = %d\n", irc); rewind(fp); for (i=0; i<NELEM; i++) { fread(product_ptr, sizeof(product), 1, fp); printf(" product %d) cat_num=%d, cost=%f\n",i,product_ptr->cat_num, product_ptr->cost); } return 0;}OUTPUTfwrite return code = 3 product 0) cat_num=2, cost=20.100000 product 1) cat_num=4, cost=40.099998 product 2) cat_num=6, cost=60.099998RANDOM ACCESS TO A FILE Used when programmer want to process or access file randomly. Functions used for Random access of file are
fseek(), ftell().
fseek() This function moves file pointer to desired location in file. It is used to index a file. it seeks specific location in file.
202
UNIT V
The syntax for fseek() is int fseek(FILE *fp, long offset,int whence);
here fp is a file pointer, offset refers to number of bytes from whence to determine new current position. whence is a positive integer number.
ftell() This function returns the current position of file pointer in the
form of number. The number is of type long. The syntax for ftell() is
ftell(FILE *fp); where fp is the file pointer. It refers to the current file pointer. If fp points beginning byte ftell() returns value 0.
rewind() This function reset file pointer to the beginning of the file. The syntax for rewind() is
void rewind(FILE *fp); where fp is a file pointer.FILE SYSTEM FUNCTIONS
These functions are used to work with file systems. 1. rename(), 2. rewind(), 3. remove() and 4. chmod() are file system functions.
rename() This function is used to rename file in argument. The syntax for rename() is
203
UNIT V
int rename(const char *oldname, const char *newname); where oldname is the current name of the file and newname is the proposed name of the file. rename() function return 0 if success. remove()
This function deletes a file. Macro translates a call to unlink. The syntax for remove() is
remove(filename); unlink()
The syntax for unlink() is int unlink(const char* filename);
This function is used to delete a file. If the file is deleted value 0 is returned. If the file is not deleted value -1 is returned. chmod()
This function changes the access mode of file. The syntax is
int chmod(const char *filename,int amode); 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.
o The argc is an argument counter that counts the number of arguments on the command line.
o The argv is an argument vector. It represents an array of character pointer that point to command line arguments.
To access command line arguments, declare the main function and parameter as main(int argc, char *argv[ ])
{ …….. }
Eg#include <stdio.h>
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");
204
UNIT V
elseprintf("One argument expected.\n");
}OUTPUTType EXIT to return to Turbo C. . .Microsoft(R) Windows DOS(C)Copyright Microsoft Corp 1990-2001.
C:\TURBOC2>F 2The argument supplied is 2
C:\TURBOC2>F1'F1' is not recognized as an internal or external command,operable program or batch file.
C:\TURBOC2>F 1The argument supplied is 1
C:\TURBOC2>F 4The argument supplied is 4
C:\TURBOC2>F 10The argument supplied is 10
C:\TURBOC2>FOne argument expected.C:\TURBOC2>Rewrite the program which copies files, ie, FCOPY.C to accept the source and destination filenames from the command line. Include a check on the number of arguments passed.Example#include<stdio.h>int main(int argc,char *argv[]){FILE *fp1,*fp2;char ch ;fp1 = fopen(argv[1],"r");if(fp1 == NULL){printf("Error in opening the file\n");exit(0);
205
UNIT V
}fp2 = fopen(argv[2],"w");if(fp2 == NULL){printf("Error in opening the file\n");exit(0);}while((ch = getc(fp1))!=EOF) //Copying the contents of src.txt to dst.txt{putc(ch,fp2);}fclose(fp1);fclose(fp2);}PREPROCESSOR
o Preprocessor is a program that process source program before it passes through the compiler.
o Preprocessor is system software that consists of special statements called directives.
o It operates under the control of directives known as preprocessor command lines.
o Preprocessor directives are placed in the source program before the main line.
o Whenever a C program is compiled, source program runs through preprocessor.
Preprocessor o Executed at the beginning of compilation process. o Do not change Original C program but creates new file. o Appear in the beginning of C program. o 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. o Preprocessor symbol should not be enclosed within quotes and should
not be enclosed with semicolon. o #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.
206
UNIT V
• 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.
TYPES OF PREPROCESSOR DIRECTIVES The types of preprocessor directives are
These facilities are controlled in a program by pre processor control lines on Directives.
Generally, the Preprocessor directives appear before the function main ( ).
But they many appear anywhere in the C Program. Preprocessor Directives follow special syntax rules. They all begin with the symbol # in column one and do not require a
semicolon at the end.A set of commonly use pre processor Directives and their functions Directives Function# define Defines a macro substitution#undef undefines a macro# include Specifies the files to be included#ifdef Test for a macro definition#endif specifies the end of # if
207
UNIT V
#ifmdef Test whether a macro is not defined#if Test a compile time condition#else Specifies alternatives when # if test fails.
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> void main(){ clrscr(); printf("%d \t %d \t %d",FIVE,SIX,SEVEN); getch(); } OUTPUT5 6 7CONDITIONAL COMPILATION
Directives permit certain segment of source code to be selectively compiled.
Directives are also called as Conditional Compilation. The Conditional directives are
208
UNIT V
• #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 #endif
If the value of constant expression is true sequence of statements are executed. if the expression value is false compiler skip the statements.int main(void) { #if 1 printf("CSE WINS\n"); #else printf("CSE ROCKS\n"); #endif return 0;}OUTPUT# if 1CSE WINS# if 0CSE ROCKSFormat 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.
209
UNIT V
The general format of #elif is #if constant expression1 statements #elif constant expression2 statements …………… #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
#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”
210
UNIT V
#include“conio.h”
#define A "X is Big"#define B "Y is Big"#include<stdio.h>void main(){ int x,y; clrscr();printf("\n Enter value for X and Y : ");scanf("%d%d",&x,&y); if(x>y) printf(A); else printf(B); getch();OUTPUT Enter value for X and Y : 23 12X is BigMEMORY 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 . 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<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)
211
UNIT V
{ printf(“Enter %d elements :”,n); for(i=0;i<n;i++) { scanf(“%d”,&a[i]); sum=sum+a[i]; } printf(“Sum of given integers is %d”,sum); } else printf(“Memory cannot be allocated”); } 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 allocatedcalloc() 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));
212
UNIT V
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 : 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 allocatedDifference Between Malloc and CallocThere are two differences. First, is in the number of arguments.
Malloc() takes a single argument (memory required in bytes), while calloc() needs two arguments.
Secondly, malloc() does not initialize the memory allocated, while calloc() initializes the allocated memory to ZERO.
calloc() allocates a memory area, the length will be the product of its parameters. calloc fills the memory with ZERO's and returns a pointer to first byte. If it fails to locate enough space it returns a NULL pointer.
i.e. ptr_var=(type *)calloc(n,s); malloc() allocates a single block of memory of REQUSTED SIZE and
returns a pointer to first byte. If it fails to locate requsted amount of memory it returns a null pointer.
Syntax: ptr_var=(cast_type *)malloc(Size_in_bytes);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.
213
UNIT V
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); 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]; }
214
UNIT V
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.