FILES in C
PREPROCESSOR directives in c
[Unit – V]
Prepared by,
D AV I D R A J U K O L L U R I
D I P L O M A [ C S E ] , B .Te c h [ C S E ] , M .Te c h [ C S E ] , ( P h D [ C S E ] )
A s s o c i a t e P r o fe s s o r, D e p t o f C S E
FILES
Definition
Purpose
Steps to Use Files
File Operations
Types of Files
Modes of Operations
File Handling Functions
Example Program
FILES
Definition: File is a Place on the Hard Disk
Which is Used to Store Huge Amount of
Data Permanently
Purpose: To Overcome The Drawback of CONSOLE I/O[keyboard & Monitor].
Drawback: Whenever Power Failure Occurs Whatever The Data Available
in Keyboard(stdin) and Monitor(stdout) Buffers Will be Simply Erased
Steps to Use FILES are:
FILE is a new Data
type Introduced
in Files
1. Use FILE Data type to Create File comes under
Pointers “stdio.h”
2. Declare File Pointers Using FILE Data
type
3. Open a File Using fopen() Function Example:
4. Filename & Mode of Operation need to #include<stdio.h>
be Specified in fopen() Function FILE *fp;
5. Perform The Specific Operation Fp= fopen(“sample”, “r”);
according to Mode of Operation printf(“%c”,fgetc(fp));
6. Close The Opened File After Completion fclose(fp);
of The Task Using fclose() function
FILE Operations
1. Creating a new file
2. Opening an existing file These are
The Major
Reading from and writing Operations We
3. Can Perform
information to a file
on Both TEXT
Appending information at & BINARY
4. Files
The End of The file
5. Closing a file
Types of FILES
TEXT File BINARY File
Binary files are mostly the .bin files
Text files are the normal .txt files
We cannot easily create using Notepad or
We can easily create using Notepad or
any simple text editors
any simple text editors.
Instead of storing data in plain text, they
When you open those files, you'll see all
store it in the binary form
the contents within the file as plain text.
You cannot easily edit or delete the
You can easily edit or delete the
contents.
contents.
Data in The Form of BINARY NUMBERS
Data in The Form of CHARACTERS
1’s and 0’s
Input , Output functions are Used to
fread & fwrite Functions are Used to
read & Write to/From the Text File
read & write To/From the Binary File
;:
FILES: Modes of Operations
TEXT file BINARY file
Read Mode: r Read Mode: rb
Write Mode: w Write Mode: wb
Append Mode: a Append Mode: ab
Read + Write Mode: r+ Read + Write Mode: rb+
Write + Read Mode: w+ Write + Read Mode: wb+
Append + Read: a+ Append + Read: ab+
If File Opened in ‘w’ Mode, New File Will be Created. If File already
Exists then Contents of That File Will be Simply Erased in ‘w’ Mode.
FILE Handling functions
S.No Function Description S.No Function Description
1 fopen() Used to open a file 10 fscanf() to read multiple data from file
2 fclose() Used to close a file 11 fprintf() To write multiple data into file
3 closeall() Used to close all files at a time
12 ferror() To check errors while opening
4 fgetc() Used to read character by 13 feof() To check end of the file
character from a file
14 fseek() To seek desired position
5 fputc() Used to write character by
character into a file 15 ftell() To know the position of pointer
6 fgetw() Used to read integers from a file 16 rewind() To move file pointer to beginning
7 fputw() Used to write integers into a file
17 fread() To read from binary file
8 fgets() Used to read strings from a file
18 fwrite() To write into binary file
9 fputs() Used to write strings into a file
Reading from a FILE
#include <stdio.h>
int main()
{ This Program illustrates
int num; The Usage of Steps to
FILE *fptr; Use Files and File
if ((fptr = fopen("C:\\program.txt","r")) == NULL) Handling Functions
{
printf("Error! opening file");
// Program exits if the file pointer returns NULL.
exit(1);
}
fscanf(fptr,"%d", &num);
printf("Value of n=%d", num);
fclose(fptr);
return 0;
}
FILE Handling functions [ Error & Random ]
S.No Function Description
1 ferror() Used to check the errors at the time of opening a file
2 feof() Used to check END of the file at the time of reading
from a file
3 fseek() Used to move file pointer to the desired position in a file
4 ftell() Used to know the position of the file pointer
5 rewind() To move file pointer to the Begining position
while(!feof(fp1))
ERROR Handling functions {
ch=fgetc(fp1)
/*write a c program to copy one file to another file*/ fputc(ch,fp2);
#include<stdio.h> }
void main() closeall()
{ }
char ch; fp2=fopen(“destination”,”r”);
FILE *fp1,*fp2; if(ferror(fp2)
fp1=fopen(“source”,”r”); {
fp2=fopen(“destination”,”w”); printf(“file not opened “);
if(ferror(fp1)||ferror(fp2)) return;
{ }
printf(“files not opened we cannot copy”); while(!feof(fp2))
return; {ch=fgetc(fp2);
} printf(“%c”,ch);}
//Continuation… fclose(fp2);
}
RANDOM ACCESS FILE Functions
There is no need to read each record sequentially, if we want to
access a particular record, C supports these functions for random
access file processing.
1. fseek()
2. ftell()
3. rewind()
RANDOM ACCESS FILE Functions
fseek(): This function is used for seeking the pointer position in the file at
the specified byte.
Syntax: fseek( file pointer, displacement, pointer position);
Where:
File pointer : It is the pointer which points to the file.
Displacement : It is positive or negative. This is the number of
bytes which are skipped backward (if negative) or forward( if
positive) from the current position. This is attached with L
because this is a long integer.
Pointer position :This sets the pointer position in the file.
RANDOM ACCESS FILE Functions
S.No. Constant & Description
1 SEEK_SET [0] Beginning position of the file
2 SEEK_CUR [1] Current position of the file
3 SEEK_END [2] End position of the file
RANDOM ACCESS FILE Functions: fseek( )
1) fseek( p,10L,0)
0 means pointer position is on beginning of the file, from this statement pointer
position is skipped 10 bytes from the beginning of the file.
2)fseek( p,5L,1)
1 means current position of the pointer position. From this statement pointer
position is skipped 5 bytes forward from the current position.
3)fseek(p,-5L,2)
2 means pointer position is at the end, From this statement pointer position is
skipped 5 bytes backward from the End position.
RANDOM ACCESS FILE Functions: fseek( )
#include <stdio.h>
int main () {
FILE *fp;
fp = fopen("file.txt","w+");
fputs(“This is: SATE’ HITAM SATYAM", fp);
fseek( fp, 7, SEEK_SET );
fputs(" C Programming Language", fp);
fclose(fp);
OUT PUT:
return(0); This is C Programming Language
}
RANDOM ACCESS FILE Functions: fseek( )
else
#include<stdio.h>
{
void main()
printf("Enter value of n to
{
read last ‘n’ characters");
FILE *fp;
scanf("%d",&n);
char ch;
fseek(fp,-n,SEEK_END);
int n;
while((ch=fgetc(fp))!=EOF)
fp=fopen("file1.c", "r");
{
if(fp==NULL)
printf("%c\t",ch);
{
}
printf("file cannot be opened");
}
}
fclose(fp);
}
RANDOM ACCESS FILE Functions: fseek( )
#include <stdio.h>
int main()
{
FILE *fp;
fp = fopen("test.txt", "r");
// Moving pointer to end
fseek(fp, 0, SEEK_END);
// Printing position of pointer
printf("%ld", ftell(fp));
return 0; OUT PUT:
} Returns the Last Position of the File
RANDOM ACCESS FILE Functions: rewind( )
The C library function void rewind(FILE *stream) sets the
file position to the beginning of the file of the given
stream.
Declaration:
Following is the declaration for rewind() function.
void rewind(FILE *stream)
Parameters
stream − This is the pointer to a FILE object that identifies
the stream.
Return Value
This function does not return any value.
RANDOM ACCESS FILE Function: rewind( )
#include <stdio.h>
int main () { rewind(fp);
char str[] = "This is HITAM"; printf("\n");
FILE *fp;
while(1) {
char ch;
fp = fopen( "file.txt" , "w" ); ch = fgetc(fp);
fwrite(str , sizeof(str) , 1 , fp ); if( feof(fp) ) {
OUT PUT:
fclose(fp); break ; Displays same
String Two times
fp = fopen( "file.txt" , "r" ); }
while(1) printf("%c", ch);
{ ch = fgetc(fp);
}
if( feof(fp) ) {
break ; fclose(fp);
} return(0);
printf("%c", ch); }
}
PREPROCESSOR directives in c
Prepared by,
D AV I D R A J U K O L L U R I
D I P L O M A [ C S E ] , B .Te c h [ C S E ] , M .Te c h [ C S E ] , ( P h D [ C S E ] )
A s s o c i a t e P r o fe s s o r, D e p t o f C S E
PRE PROCESSOR directives
C
C preprocessor
preprocessor provides
provides several
several features
features
that
that are
are not
not available
available in
in other
other highest
highest
languages.
languages. Types
By
By using
using these
these tools
tools we
we can
can make
make aa • Macro Substitution
1. Directives
program
program easy
easy to
to read,
read, modify,
modify, portable
portable and
and
efficient.
efficient.
Pre
Pre processor
processor is
is aa program
program that
that process
process the
the
2. • File Inclusion Directives
source
source code
code before
before itit passes
passes through
through the
the
compiler.
compiler. • Conditional Compilation
3. Directives
Pre
Pre processor
processor begins
begins with the ““ ## ““ symbol
with the symbol
and
and does
does not
not require
require aa semicolon
semicolon at
at the
the end.
end.
PRE PROCESSOR directives
Preprocessor Syntax/Description
Syntax: #define
Macro
This macro defines constant value and can be any of the basic data types.
Syntax: #include <file_name>
Header file inclusion The source code of the file “file_name” is included in the main program at the
specified place.
Syntax: #ifdef, #endif, #if, #else, #elif, #ifndef
Conditional compilation Set of commands are included or excluded in source program before compilation
with respect to the condition.
Syntax: #undef, #pragma
Other directives #undef is used to undefine a defined macro variable. #Pragma is used to call a
function before and after main function in a C program.
Macro substiutuion directives
Example - II
# define Japanese “З@/3: ^2~”.
#define macro_template macro_expansion # define can be used to replace a condition
# define range ( a>25 && a<50)
Macro can be used to replace a constant main()
{
# define x 25 int a=30;
if (range) { OUTPUT:
Example - I OUTPUT: printf (“\n in”); in
# define x 25 Z=40 }
void main() else
{ {
int z=15; printf (“\n out”);
z=z+x; } If we want to print a meaningless string
printf(“z=%d”z); } some ‘n’ number of times and if the
} string order of reading is difficult in that
case we can use Macro substitution
directives.
Macro substitution directives
Example – III
# define is used to replace an entire C
statement. Macros can have arguments just as functions
# define pf printf Example – IV
# define found printf (“\n virus”)
# define area (x) (3.14 * x * x)
void main()
main ()
{ OUTPUT: {
char ch; OUTPUT:
float r1=6.25, r2=2.5, a;
enter Y or N key
printf(“enter Y or N key”); a = area (r1);
122.65
scanf (“%c”, &ch); Y printf (“\n %f”,a); 19.625
if(ch == ‘y’) a = area (r2);
{ virus printf (“\n%f”, a);
found }
Note:
} Space should not be used in between
else macro_template and its arguments.
{ Macro_expansion should be placed in
printf (“\n safe”); parenthesis.
}
}
File inclusion directives //Example on #define & #include
# include “filename” ( or ) #include “stdio.h”
# include <filename> #define height 100
#define number 3.14
Angular bracket <>: If the file #define letter 'A'
name is within angular brackets #define sequence "ABC"
then the compiler checks the file #define back_char '\?'
in the current directory only. void main()
{
In string: If the file name is in the printf("value of height : %d \n", height );
string format then the compiler printf("value of number : %f \n", number );
checks not only in the current printf("value of letter : %c \n", letter );
directory but also in all specified printf("value of letter_sequence : %s \n",
corresponding directives. sequence);
printf("value of backslash_char : %c \n",
back_char); }
Conditional compilation directives
1. #ifdef
Syntax & Semantics of These
2. #if Conditional Compilation
Directives ???
3. #else
4. #elif
5. #ifndef
6. #undef
Conditional compilation directives
//Example:
1. #ifdef : # define ECE “ \n Communications”
if the macro is defined then the main() OUTPUT:
ECE
body of #ifdef will execute. { of information
#ifdef ECE
Syntax : printf (ECE);
#ifdef macro printf (“\n of information”);
……………… # endif
……………… #ifdef IT
# endif. printf(“\n Information Technology”);
#endif
Here the end of the body of ‘ifdef’ }
is # endif
Conditional compilation directives
2 .#if: //Example:
Syntax: # define x 45
# define y 110
#if <constant_expression> OUTPUT:
…… void main() hai
…… {
#endif. #if x>100
{
Note: if constant expression printf("x is greater than 100");
}
evaluates to true then the
#endif
body of #if executes. printf(“hai”);
}
Conditional compilation directives
3. #else and 4.# elif:
/*This is same as else and else #elif x < 100 && y < 100
if(condition)*/ {
# define x 45 printf("x and y are in between 0
# define y 110 and 100");
void main() }
{ #else
#if x>100 printf("y is greater than 100");
{ # endif OUTPUT:
printf("x is greater than 100"); } Y is greater than 100
} //Continuation…
Conditional compilation directives
5.# ifndef :
/*If macro is not defined then it will
execute the program.*/
6. # undef :
# define CSE “commmunication” It isused when we don’t want
# define EIE “power” to use the already defined
main() value.
{ OUTPUT:
# ifndef ECE Information Example:
/* printf (ECE); */
printf (“Information”);
#define x 45 Defined X Value
Will be Cancelled
#elif EEE #undef x
printf (“EEE”);
printf (“generator”);
# endif
}