2. Agenda
1 . Introduction to Files
2 .Types of files
3 .Using Files in C
4 .Reading data from files
5 .Writing data to files
6 .Detecting the End-of-File
7.Functions for selecting a record
randomly(File positioning)
8 .Error Handling during file operations
9 .Accepting Command line arguments
10.Renaming and Creating temporary file
3. Drawbacks of Traditional System
âą Until now we are using Console Oriented I/O functions.
âą âConsole Applicationâ means an application that has a text-based
interface. (black screen window)
âą Most applications require a large amount of data , if this data is
entered through console then it will be quite time consuming task
âą Main drawback of using Traditional I/O :- data is temporary (and
will not be available during re-execution )
4. File handling in C :
âą New way of dealing with data is file handling.
âą Data is stored onto the disk and can be retrieve whenever
require.
âą Output of the program may be stored onto the disk
âą In C we have many functions that deals with file handling
âą Collection of byte may be interpreted as â
â Single character
7. Introduction to File
âą A file is a collection of related data that a
computers treats as a single unit.
âą Computers store files to secondary storage so
that the contents of files remain intact when a
computer shuts down.
âą When a computer reads a file, it copies the file
from the storage device to memory; when it
writes to a file, it transfers data from memory
to the storage device.
âą C uses a structure called FILE (defined in
stdio.h) to store the attributes of a file.
8. Types of Files
The types of files used can be broadly classified
into two categories:
1. Text File
contains ASCII codes that performs
read/write operations.
2. Binary File
can contain non-ASCII characters
Image, audio, video, executable, etc.
9. Using in files in C
To use files in C, we must use the following
steps:
1. Declaring a file pointer variable.
2. Open the file
3. Process the file.
4. Close the file.
10. Declaring a file pointer variable
âą To access a particular file specify name of
the file that has to be used.
âą This can be accomplished by using file
pointer variable.
âą The syntax for declaring the file pointer is:
FILE
*file_pointer_name;
Ex: FILE *fp;
11. Opening a File
âą We can use the fopen( ) function to create a new
file or to open an existing file.
âą Following is the syntax of this function call:
âą Using above prototype file whose pathname is
pointed to by filename is opened in mode
specified using the mode.
FILE *fopen( const char * filename, const char * mode );
13. Code for opening a file
An error will be generated if you try to open a file that does not
exist.
FILE *fp;
fp=fopen(âstudent.txtâ,ârâ);
if(fp==NULL)
{
printf(ân the file could not be openedâ);
exit(1);
}
14. Closing a File
âą File must be closed as soon as all operations on
it completed
âą Ensures
â All outstanding information associated with
file flushed out from buffers
â All links to file broken
â Accidental misuse of file prevented
16. Reading data from files
âą C provides the following set of functions to
read data from a file:
ï fscanf( )
ï fgets( )
ï fgetc( )
ï fread( )
17. âą fscanf( )
The fscanf() function is to read formatted data
from the stream.
âą fscanf() is similar to the scanf() funtion except
that the first argument of fscanf() specifies a
stream from which to read,whereas scanf()
can only read from standard input
Syntax:
int fscanf( FILE *stream ,const char *format,âŠ);
18. âą fgets( )
The fgets() function is stands for file get string.this
function is used to get a stream.
Syntax:
âą fgetc( )
The fgetc() function returns the next character
from stream and EOF if the end of file reached
or if there is an error
Syntax:
char *fgets( char *str ,int size,FILE *stream);
int fgetc(FILE *stream);
-
19. âą fread( )
fread( ) function is used to read data from a file.
Syntax:
Remarks:
fread( ) reads a specified number of equal-sized data items
from an input stream into a block.
str = Points to a block into which data is read
size = Length of each item read, in bytes
num = Number of items read
stream = file pointer
int fread(void *str, size_t size, size_t num, FILE *stream);
21. Writing data to files
âą C provides the following set of functions to
writing data to a file:
ï fprintf()
ï fputc()
ï fputs()
ï fwrite()
22. âą fprintf( )
The fprintf( ) function is to write formatted output
to the stream.
Syntax:
int fprintf( FILE *stream ,const char *format,âŠ);
23. âą fputs( )
The fputs( ) function is used to write a line to a file
Syntax:
âą fputc( )
The fputc() function is used to write a character to
the stream.
Syntax:
int fputs( const char *str ,FILE *stream);
int fputc(int c, FILE *stream )
24. âą fwrite()
fwrite() function is used to write data to a file.
Syntax:
Remarks:
fwrite() appends a specified number of equal-sized data
items to an output file.
str = Pointer to any object; the data written begins
at ptr
size = Length of each item of data
count =Number of data items to be appended
stream = file pointer
int fwrite(const void *str, size_t size, size_t count, FILE *stream);
25. âą Simple program for reading/writing data from/to files:
#include <stdio.h>
int main ( )
{
FILE *outfile, *infile ;
int b = 5, f ;
float a = 13.72, c = 6.68, e, g ;
outfile = fopen ("testdata", "w") ;
fprintf (outfile, â %f %d %f ", a, b, c) ;
fclose (outfile) ;
infile = fopen ("testdata", "r") ;
fscanf (infile,"%f %d %f", &e, &f, &g) ;
printf (â %f %d %f n ", a, b, c) ;
printf (â %f %d %f n ", e, f, g) ;
}
13.720000,5,6.680000
13.720000,5,6.680000
26. Detecting End-of-File
There are a number of ways to test for the end-of-file
condition. Another way is to use the value returned by
the fscanf () function.The prototype of feof() can be
given as :
int feof(FILE *fp);
Ex: FILE *fptr1;
int istatus ;
istatus = fscanf (fptr1, "%d", &var) ;
if ( istatus == feof(fptr1) )
{
printf ("End-of-file encountered.nâ) ;
}
27. Error handling during file operation
âą Typical errors that occur
â trying to read beyond end-of-file
â trying to use a file that has not been opened
â perform operation on file not permitted by âfopenâ mode
â open file with invalid filename
â write to write-protected file
28. âą ferror()
The library function is used to check for error in the
stream.
âą clearerr()
The function is used to clear EOF and error
indicator for the stream.
âą perror()
It stands for print error.
Syntax: int ferror(FILE *stream)
Syntax: void clearerr(FILE *stream)
Syntax: void perror(const char *s)
29. âą The following example shows the usage of perror( ) function.
#include <stdio.h>
#include <errno.h>
#include <string.h>
extern int errno ;
int main () {
FILE * pf;
int errnum;
pf = fopen ("unexist.txt", "rb");
if (pf == NULL) {
errnum = errno;
fprintf(stderr, "Value of errno: %dn", errno);
perror("Error printed by perror");
fprintf(stderr, "Error opening file: %sn", strerror( errnum ));
}
else {
fclose (pf) ;
}}
Output :
Error reading
from file
"file.txt"
30. Functions for selecting record
randomly
âą Functions that are used to randomly access a
record stored in a binary file. This functions
include:
âą fseek( )
âą ftell( )
âą rewind( )
âą fgetpos( )
âą fsetpos( )
31. âą fseek()
The function fseek() reposition a binary stream.
âą fseek() seeks the file position for stream; a subsequent read
or write will access data beginning at the new position.
âą For a binary file, the position is set to offset characters from
origin, which may be
SEEK_SET (beginning),
SEEK_CUR (current position) or
SEEK_END (end of file).
For a text stream, offset must be zero, or a value returned by
ftell (in which case origin must be set to SEEK_SET).
âą SEEK_SET,SEEK_CUR and SEEK_END are defined
constants with value 0,1 and respectively.
Syntax : int fseek(FILE *stream, long offset, int origin)
32. The following example shows the usage of
fseek() function.
#include <stdio.h>
int main ()
{
FILE *fp;
fp = fopen("file.txt","w+");
fputs("D is not programming language", fp);
fseek( fp, 7, SEEK_SET );
fputs(" C Programming Language", fp);
fclose(fp);
return(0);
}
Output : C programming
language
33. âą ftell( )
ftell( ) is used to find the current position of the file from
the beginning of the file.
âą If successful, ftell() function returns the current
file position(in bytes) for stream.
âą In case of error,ftell() returns -1.
âą ftell() is useful when we have to deal with text
files for which position of the data cannot be
calculated.
Syntax: long int ftell(FILE *stream)
34. #include <stdio.h>
int main ()
{
FILE *fp;
int len;
fp = fopen("file.txt", "r");
if( fp == NULL )
{
perror ("Error opening file");
return(-1);
}
fseek(fp, 0, SEEK_END);
len = ftell(fp);
fclose(fp);
printf("Total size of file.txt = %d bytesn", len);
return(0);
}
Let us assume we have a text file file.txt, which has the following
content â
This is tutorialspoint.com
Output : Total size of file.txt =
27 bytes
35. âą rewind()
rewind() is used to reposition the file pointer to
the
beginning of the file.
âą fgetpos()
fgetpos() records the file position in stream in
*pos, for subsequent use. The type fpos_t is
suitable for recording such values.
Syntax: void rewind(FILE *stream)
rewind is equivalent to fseek(fp, OL, SEEK_SET);
Syntax: int fgetpos(FILE *stream, fpos_t*pos)
36. âą fsetpos()
fsetpos() positions stream at the position recorded by
fgetpos in *pos.
âą remove()
The remove() function,as the name suggest is
used to erase a file.
Syntax : int fsetpos(FILE *stream,const fpos_t *pos)
Syntax: int remove (const char *filename);
37. Command Line arguments
âą Command line arguments are given after name of
program in command line operating system such as
DOS or LINUX and are passed into the program
from the operating system.
main ( int argc, char *argv[])
âą argc â gives a count of number of arguments
(including program name)
âą char *argv[] defines an array of pointers to character
(or array of strings)
âą argv[0] â program name
âą argv[1] to argv[argc -1] give the other arguments as
strings
38. Renaming a file
âą rename( )
The function rename( ) as the name suggests is
used to rename a file.
If the oldname specifies pathname of a file that is
not directory,the new name shall also not point
to the pathname of a directory.
Syntax: int rename(const char *old name,const
char * new name)
39. Example:
#include <stdio.h>
int main ()
{
int ret;
char oldname[] = "file.txt";
char newname[] = "newfile.txt";
ret = rename(oldname, newname);
if(ret == 0)
{
printf("File renamed successfully");
}
else
{
printf("Error: unable to rename the file");
}
return(0);
}
Output: File renamed
successfully
40. Creating a Temporary file
âą tmpfile()
The tmpfile() function is used to create a temporary
file.
A file created with tmpfile() will be automatically
deleted when all references to the file are closed.
On success,tmpfile( ) will return a pointer to the
stream of the file name that is created.
Syntax: FILE*tmpfile(void);
41. The following example shows the usage of tmpfile()
function.
#include <stdio.h>
int main ()
{
FILE *fp;
fp = tmpfile();
printf("Temporary file createdn");
/* you can use tmp file here */
fclose(fp);
return(0);
}
Output: Temporary file
created
43. Introduction
âą The C Preprocessor is not a part of the compiler,
but is a separate step in the compilation process.
44. Three kinds of directives
âą File inclusion
â #include
âą Macros
â #define
âą Conditional compilation
â #if, #ifdef, #ifndef, #elif, #else, #endif
ïŒ Always starts with a line with â#â
ïŒ Can appear anywhere in a program
46. File Inclusion
âą Allow a program or a moduleâs implementation to use certain
header file.
âą An interface or a header file contains declarations for a
module
âą Name of the header file should end in .h
âą User-define header files â ... â
#include âsample.hâ
âą System header files: < ... >
#include <stdio.h>
47. Ex: /* program to call the function defined in âsample.câ file */
#include<stdio.h>
#include<conio.h>
#include âsample.câ
void main ( )
{
clrscr ( );
display ( );
}
Output: welcome to c
âą /* file sample.c*/
int display( )
{
printf(âwelcome to câ);
return 0;
}
48. Macro Substitution
ï Provide parameterized text substitution
ï The syntax of #define directive is as follows
Example : #define MAXLINE 120
#define lower(c) ((c)-`Aâ+âaâ)
ï Macro replacement
char buf[MAXLINE+1];
becomes
char buf[120+1];
ï c = lower(buf[i]);
becomes
c = ((buf[i])-`Aâ+âaâ);
#define identifier <substitute text>
49. Macros: Use â(â and â)â
ï¶ Always parenthesize macro parameters in definition
#define plusone(x) x+1
i = 3*plusone(2);
becomes
i = 3*2+1
#define plusone(x) ((x)+1)
i = 3*plusone(2);
becomes
i = 3*((2)+1)
50. Conditional Compilation
ïŒ One source for many platforms or many cases
ïŒ Need to have special source for specific situations
ïŒ Conditional compilation
#ifdef <identifier>
#ifndef <identifier>
#if <expr>
#elif <expr>
#else
#endif
ïŒ Removing macro definitions
#undef <identifier>
51. âą The syntax of the #ifdef directive is:
#ifdef <identifier>
{
statements1;
statements2;
}
#else
{
statements3;
statements4;
}
#endif
52. âą Example: /* program to use conditional compilation statement to
check identifier is defined or not */
#include<stdio.h>
#include<conio.h>
#define LINE 1
void main ( )
{
clrscr ( );
#ifdef LINE
printf(â This is line number oneâ);
#else
printf(â This is line number twoâ);
#endif
getch( );
}
Output: This
is line
number one
53. The #ifndef directive
The syntax of the #ifndef directive is given below:
âą
#ifndef <identifier>
{
statements1;
statements2;
}
#else
{
statements3;
statements4;
}
#endif
54. Ex: /* program to use conditional compilation directive
#ifndef */
âą
#include<stdio.h>
#include<conio.h>
#define LINE
void main ( )
{
clrscr ( );
#ifndef LINE
printf(â Macro is not definedâ);
#else
printf(âMacro is definedâ);
#endif
getch( );
}
Output: Macro is not
defined
55. Use of #if, #elif, #else and #endif
The preprocessor directives #if, #elif, #else and #endif allows to
conditionally compile a block of code based on predefined symbols.
Example: Program to illustrate this concept.
#include<stdio.h>
#define MAX 100
void main()
{
#if(MAX)
printf("MAX is defined");
#else
printf ("MAX is not defined");
#endif
}
Output:
MAX is defined