Uploaded by nisha auti

File Handling in C by ANA

advertisement
File Handling in C
Dr. Nisha Auti
Console oriented Input/Output
• Console oriented – use terminal (keyboard/screen)
• scanf(“%d”,&i) – read data from keyboard
• printf(“%d”,i) – print data to monitor
• Suitable for small volumes of data
• Data lost when program terminated
Real-life applications
• Large data volumes
• E.g. population records, student record, customer record etc.
• Need for flexible approach to store/retrieve data
• Concept of files
Files
• A file is a container in computer storage devices used for storing data
• File – place on disc where group of related data is stored
• E.g. your C programs, executables
• High-level programming languages support file operations
•
•
•
•
•
Naming
Opening
Reading
Writing
Closing
Why files are needed?
• When a program is terminated, the entire data is lost. Storing in a file
will preserve your data even if the program terminates.
• If you have to enter a large number of data, it will take a lot of time to
enter them all.
However, if you have a file containing all the data, you can easily
access the contents of the file using a few commands in C.
• You can easily move your data from one computer to another without
any changes.
File Operations
• In C, you can perform four major operations on files, either text or
binary:
• Creating a new file
• Opening an existing file
• Closing a file
• Reading from and writing information to a file
Different operations that can be performed
on a file
• Creation of a new file (fopen with attributes as “a” or “a+” or “w” or
“w++”)
• Opening an existing file (fopen)
• Reading from file (fscanf or fgets)
• Writing to a file (fprintf or fputs)
• Closing a file (fclose)
Functions for file handling
Opening File: fopen()
• fopen() function is used to open a file.
• The syntax of the fopen() is given below.
• FILE *fopen( filename, mode );
• The fopen() function accepts two parameters:
• The file name (string). If the file is stored at some specific location,
then we must mention the path at which the file is stored. For
example, a file name can be like "c://some_folder/some_file.ext".
• The mode in which the file is to be opened. It is a string.
Example 1: Write to a text file
Read from a text file
Download