Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
14 views9 pages

Unit 5 File Handling

Download as docx, pdf, or txt
Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1/ 9

Fgetc: fgetc() is used to obtain input from a file single character at a time.

This function returns the ASCII code of the character read by the function. It
returns the character present at position indicated by file pointer. After
reading the character, the file pointer is advanced to next character. If
pointer is at end of file or if an error occurs EOF file is returned by this
function.

Syntax:
int fgetc(FILE *pointer)
pointer: pointer to a FILE object that identifies
the stream on which the operation is to be performed.

Eg:
#include <stdio.h>
#include <stdlib.h>

int main()
{
FILE *ptr=NULL;
ptr=fopen("abc.txt","r");
char c=fgetc(ptr);
printf("The read char is %c",c);
return 0;
}

Fgets:
The fgets() reads a line from the specified stream and stores it into the string
pointed to by str. It stops when either (n-1) characters are read, the newline
character is read, or the end-of-file is reached, whichever comes first.

Syntax
char *fgets (char *str, int n, FILE *stream);
Parameters
str: Pointer to an array of chars where the string read is copied.
n: Maximum number of characters to be copied into str (including the
terminating null character).
*stream: Pointer to a FILE object that identifies an input stream.

Eg:
int main()
{
FILE *ptr=NULL;
ptr=fopen("abc.txt","r");
char str[4];
fgets(str,3,ptr);
printf("The read string is %s",str);

fclose(ptr);
return 0;

fputc / fgets:

fputc: The C library function int fputc(int char, FILE


*stream) writes a character (an unsigned char) specified by the
argument char to the specified stream and advances the position
indicator for the stream.

Declaration
Following is the declaration for fputc() function.

int fputc(int char, FILE *stream)

Parameters
 char − This is the character to be written. This is passed as its
int promotion.
 stream − This is the pointer to a FILE object that identifies the
stream where the character is to be written.

fputs:
The C library function int fputs(const char *str, FILE
*stream) writes a string to the specified stream up to but not
including the null character.
Declaration
Following is the declaration for fputs() function.

int fputs(const char *str, FILE *stream)

Parameters
 str − This is an array containing the null-terminated sequence
of characters to be written.
 stream − This is the pointer to a FILE object that identifies the
stream where the string is to be written.
Eg:
#include <stdio.h>
#include <stdlib.h>

int main()
{
FILE *ptr=NULL;
ptr=fopen("abc.txt","w");
fputc('o',ptr); //single quoted text for char
fputs("Good morning",ptr); //double quoted text for string
fclose(ptr);
return 0;
}

r+ mode: it overwrites the content of existing file at the starting of file


only. Writing is done using this mode on existing file.

Eg:
#include <stdio.h>
#include <stdlib.h>
int main()
{
FILE *ptr=NULL;
ptr=fopen("abc.txt","r+"); //r+mode
fputc('o',ptr); //single quoted text for char
fputs("Good morning",ptr); //double quoted text for string
fclose(ptr);
return 0;
}

a+ mode: it appends the new content on file at the end of file.

#include <stdio.h>
#include <stdlib.h>

int main()
{
FILE *ptr=NULL;
ptr=fopen("abc.txt","a+"); //a+mode
fputc('o',ptr); //single quoted text for char
fputs("Good morning",ptr); //double quoted text for string
fclose(ptr);
return 0;
}

W+ mode: writes the content on existing file.

1. Compare the features of Sequential File, Index Sequential File


and Direct Access File.

2. What is the difference between Binary File and Text File? Explain
different file opening modes in C++.
3. Write a pseudo ‘C++’ code to implement sequential file in C++.
(minimum three primitive operations expected)

4. Write a short note on (any two)


a. Binary File vs Text File
b. Sequential File
c. Coral rings.

5. Define what constitutes a binary file. Elaborate on the different


file opening modes provided by C++ specifically designed for
handling binary files.

6. Develop a pseudo 'C++' code to implement sequential file. Write


code to search and delete a record in a file.

File handling in C++

we have been using the iostream standard library, which


provides cin and cout methods for reading from standard input and
writing to standard output respectively.
Now we can know how to read and write from a file. This requires
another standard C++ library called fstream, which defines three
new data types

Sr.N
Data Type & Description
o

ofstream
1 This data type represents the output file stream and is used to create files and to write
information to files.

ifstream
2
This data type represents the input file stream and is used to read information from files.

fstream
This data type represents the file stream generally, and has the capabilities of both
3
ofstream and ifstream which means it can create files, write information to files, and read
information from files.

To perform file processing in C++, header files <iostream> and


<fstream> must be included in your C++ source file.

Opening a File
A file must be opened before you can read from it or write to it.
Either ofstream or fstream object may be used to open a file for
writing. And ifstream object is used to open a file for reading
purpose only.

Following is the standard syntax for open() function, which is a


member of fstream, ifstream, and ofstream objects.

void open(const char *filename, ios::openmode mode);

Here, the first argument specifies the name and location of the file
to be opened and the second argument of the open() member
function defines the mode in which the file should be opened.

Sr.N
Mode Flag & Description
o

1 ios::app
Append mode. All output to that file to be appended to the end.

ios::ate
2
Open a file for output and move the read/write control to the end of the file.

ios::in
3
Open a file for reading.

ios::out
4
Open a file for writing.

ios::trunc
5
If the file already exists, its contents will be truncated before opening the file.

You can combine two or more of these values by ORing them


together. For example if you want to open a file in write mode and
want to truncate it in case that already exists, following will be the
syntax −

ofstream outfile;
outfile.open("file.dat", ios::out | ios::trunc );

Similar way, you can open a file for reading and writing purpose as
follows −

fstream afile;
afile.open("file.dat", ios::out | ios::in );

Closing a File
When a C++ program terminates it automatically flushes all the
streams, release all the allocated memory and close all the opened
files. But it is always a good practice that a programmer should
close all the opened files before program termination.

Following is the standard syntax for close() function, which is a


member of fstream, ifstream, and ofstream objects.

void close();

Writing to a File
While doing C++ programming, you write information to a file from
your program using the stream insertion operator (<<) just as you
use that operator to output information to the screen. The only
difference is that you use an ofstream or fstream object instead of
the cout object.

Reading from a File


You read information from a file into your program using the stream
extraction operator (>>) just as you use that operator to input
information from the keyboard. The only difference is that you use
an ifstream or fstream object instead of the cin object.

Read and Write Example


Following is the C++ program which opens a file in reading and
writing mode. After writing information entered by the user to a file
named afile.dat, the program reads information from the file and
outputs it onto the screen −

Live Demo
#include <fstream>
#include <iostream>
using namespace std;

int main () {
char data[100];

// open a file in write mode.


ofstream outfile;
outfile.open("afile.dat");

cout << "Writing to the file" << endl;


cout << "Enter your name: ";
cin.getline(data, 100);

// write inputted data into the file.


outfile << data << endl;

cout << "Enter your age: ";


cin >> data;
cin.ignore();

// again write inputted data into the file.


outfile << data << endl;

// close the opened file.


outfile.close();

// open a file in read mode.


ifstream infile;
infile.open("afile.dat");

cout << "Reading from the file" << endl;


infile >> data;

// write the data at the screen.


cout << data << endl;

// again read the data from the file and display it.
infile >> data;
cout << data << endl;

// close the opened file.


infile.close();

return 0;
}

When the above code is compiled and executed, it produces the


following sample input and output −

O/P: Writing to the file


Enter your name: Zara

You might also like