0% found this document useful (0 votes)
10 views

Lec 10 File Operations

Uploaded by

dennismwenda342
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
10 views

Lec 10 File Operations

Uploaded by

dennismwenda342
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 6

Chapter 10

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

int fputs( const char *s, FILE *fp ); for string


Example
#include <stdio.h>
main()
{
FILE *fp;
fp = fopen("/tmp/test.txt", "w+");
fprintf(fp, "This is testing for fprintf...\n");
fputs("This is testing for fputs...\n", fp);
fclose(fp);
}
Read operations
For character use int fgetc( FILE * fp );
For Strings use char *fgets( char *buf, int n, FILE *fp );

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

You might also like