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