Presentation is loading. Please wait.

Presentation is loading. Please wait.

File Handling In C By - AJAY SHARMA. We will learn about- FFile/Stream TText vs Binary Files FFILE Structure DDisk I/O function OOperations.

Similar presentations


Presentation on theme: "File Handling In C By - AJAY SHARMA. We will learn about- FFile/Stream TText vs Binary Files FFILE Structure DDisk I/O function OOperations."— Presentation transcript:

1 File Handling In C By - AJAY SHARMA

2 We will learn about- FFile/Stream TText vs Binary Files FFILE Structure DDisk I/O function OOperations on File (open,close,read,write rename etc.) FFormatted I/O function LLow level Disk I/O

3 What is a 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

4 Cont… Files are not only used for data. Our programs are also stored in files. In order to use files we have to learn about File I/O i.e. how to write information to a file and how to read information from a file. File I/O done by STREAM.

5 What is Stream ? Stream is not a hardware. It is linear queue which connect file to program and passes block of data in both direction. We can associate a stream with a device (i.e. the terminal) or with a file. We can also define stream as source of data.This source can be A file Hard disk, CD, DVD or I/O devices etc.

6 Types of Stream C supports two types of Stream – Text Stream – Binary Stream

7 Text vs Binary How newlines (\n) are stored. How end of file is indicated. How numbers are stored in the file.

8 System-Created Streams C automatically creates five streams that it opens and closes automatically for us in order to communicate with the terminal: We cannot re-declare these streams in our programs. Standard File PointerDescription Stdin Standard input device(keyborad) StdoutStandard output device(vdu) StderrStandard error device (vdu) Stdaux Standard auxiliary device (serial port) StdpmStandard printing device ( patallel printer)

9 How to access a File ? A file pointer is needed in order to read or write files. File pointer points to a Structure(FILE)that contains info about the file. FILE structure is declared in stdio.h header file FILE *fp

10 FILE Structure typedef struct { short level; unsigned flags; char fd; unsigned char hold; short bsize; unsigned char *buffer, *curp; unsigned istemp; short token; } FILE;

11 File Structure contains info about : Current size of file Location in memory Character pointer points to character to be read

12 Disk I/O functions Disk I/O Text Formatte d Low LevelHigh Level Binary Formatte d Unformatte d

13 Opening a File fopen() function opens a stream for use and links a file with that stream. A file pointer associated with that file is then returned by the fopen() function. The prototype for the fopen() is FILE *fopen(const char *filename, const char *mode);

14 3 Tasks of fopen() File *fp; fp=fopen(“file name”, “mode”); It searches on the disk the file to be opened. If file present then load it from the disk into memory or if file is not present returns a NULL. It sets up a character pointer which points to the first character

15 More on fopen() The file mode tells C how the program will use the file

16 File opening Mode Mode Description “r”It opens the file in read mode If file exists,the pointer is positioned at the beginning, else return NULL “w”It opens the file in write mode If file exist, pointer is positioned at the beginning, file overwrite, else create a new file. “a”It opens the file in append mode If file exist, pointer is positioned at the end,if file doesn't exist new file is created.

17 More on File opening mode

18 Closing a File When we finish with a mode, we need to close the file before ending the program or beginning another mode with that same file. Closing a stream flushes out any associated buffer, an important operation that prevents loss of data when writing to a disk. int fclose (FILE *fp); The fcloseall() function closes all the open files

19 Reading a Character The fgetc() function is used for reading character from a file opened in read mode, using fopen(). The prototype for fgetc() is - int fgetc(FILE *fp); If the end of file is reached, fgetc() returns EOF.

20 Writing a Character Streams can be written to either character by character or as a string The function used for writing characters to a file is fputc(). The prototype for this is - int fputc(int ch, FILE *fp); The fputc() function writes a character to specified stream at the current file position and advances the file pointer.

21 String I/O The functions fputs() and fgets() are used write and read character strings to and from disk file. The prototypes for the above functions are – int fputs(const char *str, FILE *fp); char *fgets( char *str, int length, FILE *fp); The fputs() function returns EOF if an error occurs. The fgets() function returns a null pointer if an error occurs.

22 Writing a block of Data Used to read and write an entire block of data to and from a file. Referred to as unformatted read and write functions. The prototypes for these functions are – fread()- size_t fread(void *buffer, size_t num_bytes, size_t count FILE *fp); fwrite()- size_t fwrite(const void *buffer, size_t num_bytes, size_t count FILE *fp);

23 More on fwrite()/fread() The fread() function returns the number of items read. The fwrite() function returns the number of items written. As long as the file is open for binary operations, fread() and fwrite() can read and write any type of information. One of the most useful applications of fread() and fwrite() is reading and writing user-defined data types like structures.

24 More on fread() and fwrite() struct emp { char name[40] ; int age ; float bs ; } ; struct emp e ; fwrite ( &e, sizeof ( e ), 1, fp ) Size of the struture in bytes Address of the structure No of structure Pointer to the file

25 Formatted I/O function fprintf() & fscanf() These functions are similar to printf() and scanf() except that they operate with files. The prototypes of fprintf() and fscanf() are: int fprintf(FILE *fp, const char *control_string, …); int fscanf(FILE *fp, const char *control_string, …);

26 Current Active pointer In order to keep track of the position where I/O operations Take place a pointer is maintained in the file structure. Whenever a character is read from or written to the stream, The current active pointer is advanced. The current location of the current active pointer can be found with the help of the ftell() function long int ftell( FILE *fp); It returns this position as a long int which is an offset from the beginning of the file

27 Setting current position We can perform random read and write operations using the C I/O system with the help of fseek( ),which sets the file position indicator The prototype of the fseek() function is – int fseek( FILE *fp, long int offset, int origin);

28 More on SEEK OriginFile location SEEK_SET or 0Beginning of file SEEK_CUR or 1Current file position pointer SEEK_END or 2End of file

29 Rewind Function The rewind() function resets the file position indicator to the beginning of the file. The syntax for rewind() is : rewind(fp);

30 Erasing a File The remove() function erases the specified file. The prototype of the remove() function is – int remove (char *filename); It returns 0 if successful else returns a non zero value

31 ferror() function The ferror() determines whether a file operation has produced an error. Its prototype is : int ferror(FILE *fp);

32 Flushing Stream The fflush() function clears the buffer. The action of flushing depends upon the file type. The prototype for this particular function is : int fflush (FLUSH *fp);

33 More on Flushing Stream The fflush() writes the contents of any buffered data to the file associated with fp. The fflush() function, with a null, flushes all the files opened for output.

34 Low level Disk I/O Advantages these functions parallel the methods that the OS uses to write to the disk, they are more efficient than the high level disk I/O functions. there are fewer layers of routines to go through, low level I/O functions operate faster than their high level counterparts.

35 More on Low level I/O There is only one way data can be written or read in low level disk I/O functions as a buffer full of bytes. Declaring the Buffer :- char buffer[512] ; The size of this buffer is important for efficient operation.

36 What is a Buffer? A buffer is a “special work area” that holds data as the computer transfers them to/from memory. Buffers help to synchronize data the physical devices with the program. The physical requirements of the devices can deliver more data for input than a program can use at any one time. The buffer handles the overflow data until a program can use it. Moreover, the buffer also holds data until it is efficient to write that data to the storage device for output.

37 Opening a File Mode Description O_APPENDOpens a file for appending O_CREATCreates a new file for writing (has no effect if file already exists) O_RDONLY Creates a new file for reading only O_RDWR Creates a file for both reading and writing O_WRONLYCreates a file for writing only O_BINARYCreates a file in binary mode O_TEXT Creates a file in text mode

38 cont... file_handler = open(source,opening mode); open( ) returns an integer value called ‘file handle’. This is a number assigned to a particular file, which is used thereafter to refer to the file. If open returns -1 means fine couldn't be successfully opened.

39 Interaction between Buffer and File bytes = read(file_handler,buffer,256); Read() function returns no of bytes actually read. Write() used for write into the file.

40


Download ppt "File Handling In C By - AJAY SHARMA. We will learn about- FFile/Stream TText vs Binary Files FFILE Structure DDisk I/O function OOperations."

Similar presentations


Ads by Google