Lec 10 File Operations
Lec 10 File Operations
FILE I/0
Introduction
• A file represents a sequence of bytes, does not matter if it is a text file
or binary file.
• C programming language provides access on high level functions as
well as low level (OS level) calls to handle file on your storage devices
• The main operations of a file : Open/Create , close , Read or Write
Opening Files
You can use the fopen( ) function to create a new file or to open an
existing file, this call will initialize an object of the type FILE, which
contains all the information necessary to control the stream
FILE *fopen( const char * filename, const char * mode );
Modes of Opening files
Closing a File
To close a file, use the fclose( ) function. The prototype of this function is:
int fclose( FILE *fp );
The fclose( ) function returns zero on success, or EOF if there is an error in closing the file. This function
actually, flushes any data still pending in the buffer to the file, closes the file, and releases any memory
used for the file. The EOF is a constant defined in the header file stdio.h.
Write operations
• The write operations can either be character or String with the character or a value on successful
write or EOF in an error
int fputc( int c, FILE *fp ) ; for Character
Example
#include <stdio.h>
main()
{
FILE *fp;
char buff[100];
fp = fopen("/tmp/test.txt", "r");
fscanf(fp, "%s", buff);
printf("1 : %s\n", buff );
fgets(buff, 255, (FILE*)fp);
printf("2: %s\n", buff );
fgets(buff, 255, (FILE*)fp);
printf("3: %s\n", buff );
fclose(fp);
}
Exercise
• Create a Program to Create a File Called Students with particulars of
Name , No, Gender , area of study .
• Populate the File with 20 students record and Read the File to show
the content