This document discusses file handling in C++. It explains that file handling allows storing data permanently on a computer's hard disk. The key steps for file handling are naming a file, opening it, writing data, reading data, and closing the file. It also discusses various file handling functions like fstream, ifstream, ofstream and their usage for opening, reading, writing and closing files. Functions like get(), put(), tellg(), seekg() and their usage with file streams are explained. Examples are provided to demonstrate reading from and writing to files.
This document discusses file input/output (I/O) in C++. It covers:
1) Stream classes like ifstream and ofstream that represent input/output data flows to files.
2) Formatted and binary I/O - formatted stores data as text which is inefficient for large numbers, while binary stores directly in memory format.
3) Reading and writing objects using binary I/O by casting object addresses and writing the full object size in bytes.
This document provides an overview of file and stream input/output (I/O) in C++. It discusses how stream classes can be used to read from and write to files, with examples showing how to open files, write formatted data to files using output streams, and read data from files using input streams. Key classes for file I/O like ifstream, ofstream, and fstream are described. Techniques for handling different data types like characters, strings, and integers are also covered.
This document discusses object-oriented programming (OOP) and file input/output in C++. It describes how files can be accessed sequentially or randomly. Random access files allow records to be accessed in any order, while sequential files require processing records in sequence. The document also provides code examples for creating and writing text files, reading files with characters and strings, and reading/writing binary files with user-defined class objects.
The document discusses the problems with header files in C/C++ and proposes a module system as an alternative. It describes how a module system would work, including importing modules, selective importing of submodules, and how modules would be written. Key advantages of a module system include avoiding header fragility, improving performance by reducing compilation dependencies, and making the compilation model scalable. The document also outlines a transitional approach to implementing modules by building them from existing header files using module maps.
The document discusses file handling in C++. It describes how to perform input/output operations on files using streams. There are three types of streams - input streams, output streams, and input/output streams. Key functions for file handling include open(), close(), get(), getline(), read(), write(), tellg(), tellp(), seekg(), seekp(), and eof(). An example program demonstrates how to add, view, search, delete, and update records in a binary file using file handling functions.
This document discusses working with files in C++. It covers opening and closing files using constructors and the open() function. It describes using input and output streams to read from and write to files. It also discusses the different file stream classes like ifstream, ofstream, and fstream and their functions. Finally, it mentions the different file opening modes that can be used with the open() function.
This document discusses C++ files and streams. It covers reading and writing both sequential and random access files in C++. Some key points covered include:
- C++ views files as sequences of bytes with an end-of-file marker
- Streams are used to perform file I/O and are associated with file objects
- Sequential files are read or written to in a linear fashion while random access files allow direct access to records
- Functions like read(), write(), seekg(), seekp() are used to read from and write to files at specific positions.
The document describes an online student management system implemented using C++ that allows storing student data in a text file database. The system provides different views of the data for users like students, faculty, proctors and administrators. It allows adding, editing and viewing student details like registration number, name, marks in subjects and proctor ID. The source code implements the various user interfaces and file handling for performing CRUD operations on the text file database according to the user type.
The document discusses various ways of interacting with hardware and low-level operations in C programming. It covers opening files, reading and writing files, modifying files, calling BIOS and DOS routines, manipulating CPU registers, and interacting directly with hardware through standard library functions. Examples are provided for copying files, positioning the cursor, clearing the screen, deleting and renaming files by calling interrupt functions. Structures and unions are also explained with examples.
#include
#include
#include
#include
#include \"textFile.hpp\"
using namespace std;
void displayHelp();
bool isInteger(const string &s);
bool askSave();
int main(int argc, const char * argv[]) {
int resultCode = 0;
// Convert to a vector.
vector args(argv, argv + argc);
// Process arguments, must be 1 argument, otherwise exit with code 1.
if (args.size() < 2) {
cout << \"Missing command line argument!\" << endl;
cout << \"Usage: ./myEditor \" << endl;
resultCode = 1;
} else {
string fileName = args[1];
textFile dataFile(fileName);
// Check if the file is ok to use, if it is, lets go.
if (!dataFile.checkFile()) {
resultCode = 2;
} else {
// We can now assume the file is good, so we can work with it.
dataFile.loadFile();
// Display some text to help the user.
displayHelp();
// Now get user input.
bool done = false;
string userInput = \"\";
while (!done) {
cout << \"> \";
getline(cin, userInput);
char cmd = tolower(userInput.c_str()[0]);
char cmd2 = \' \';
if (userInput.size() > 1) {
cmd2 = userInput.c_str()[1];
}
// This check makes sure the command format is correct
// so that commands don\'t fire off by mistake.
if (strncmp(&cmd, \" \", 1) != 0 && strncmp(&cmd2, \" \", 1) == 0) {
switch(cmd) {
case \'q\': {
done = true;
break;
}
case \'i\': {
unsigned long lineIndex = dataFile.textLines() + 1;
string newLine;
if (userInput.size() > 1) {
string cmdArg = userInput.substr(2);
lineIndex = stol(cmdArg);
}
cout << to_string(lineIndex) << \"> \";
getline(cin, newLine);
dataFile.insertLine(lineIndex - 1, newLine);
break;
}
case \'d\': {
if (userInput.size() > 1) {
unsigned long lineIndex;
string cmdArg = userInput.substr(2);
lineIndex = stol(cmdArg);
dataFile.removeLine(lineIndex - 1);
}
break;
}
case \'l\': {
for (int x = 0; x < dataFile.textLines(); x++) {
cout << to_string(x + 1) << \"> \" << dataFile.getLine(x) << endl;
}
break;
}
case \'h\': {
displayHelp();
break;
}
case \'s\': {
dataFile.saveFile();
break;
}
}
}
}
// Ask about saving the file before exiting.
bool save = askSave();
if (save) {
dataFile.saveFile();
}
cout << \"Thank you for using myEditor.\" << endl;
}
}
return resultCode;
}
/*
Asks the user if they\'d like to save or not, returns true if they do. Anything
other than \"y\" or \"Y\" will be interpreted as a negative answer.
*/
bool askSave()
{
bool result = false;
string userInput = \"\";
cout << \"Do you wan to save the change? (Y - yes; N - no) \";
getline(cin, userInput);
userInput = tolower(*userInput.c_str());
if (strncmp(userInput.c_str(), \"y\", 1) == 0) {
result = true;
}
return result;
}
/*
Displays help text.
*/
void displayHelp()
{
cout << \"Welcome to my text editor.\" << endl;
cout << \"\\tTo insert text at the end of the file, type \'I\'\" << endl;
cout << \"followed by the text.\" << endl;
cout << \"\\tTo insert text at a certain line number, type \'I\'\" << endl;
cout << \"followed by a space and the desired line number.\" << endl;
cout << \"\\tTo delete a line, type \'D\' followed by a space and the\" << endl;
cou.
Basic file operations in C++ involve opening, reading from, and writing to files. The key classes for input/output with files are ofstream for writing, ifstream for reading, and fstream for both reading and writing. A file must first be opened before performing any operations on it. Common operations include writing data to files with put() or write(), reading data from files with get() or read(), and closing files after completion. Proper opening modes and error handling should be used to ensure successful file input/output.
Managing console i/o operation,working with filesramya marichamy
This document discusses C++ stream classes and file input/output. It covers the key stream classes like istream, ostream and iostream. It describes how to use stream manipulators and member functions to format console I/O. It also covers file streams like ifstream, ofstream and fstream for reading from and writing to files. Functions like open(), get(), put(), read(), write() are described for file I/O operations. Common file I/O tasks like displaying, modifying and deleting file contents are mentioned.
This document discusses C++ stream classes and file input/output. It covers the key stream classes like iostream, istream, ostream and their functions. It also discusses file classes like ifstream, ofstream and fstream that are used for file input/output. It provides examples of reading from and writing to files using these classes and their functions like open(), get(), put() etc. It mentions how file pointers are used to manipulate file positions for input/output operations.
The document discusses C++ file input/output (I/O) using fstream header file. It provides examples of writing data to a file using ofstream, reading data from a file using ifstream, and reading/writing a struct to a file. The examples demonstrate opening, reading, writing and closing files, as well as using functions to read and write data. The last example adds an expire attribute to the struct and reads/writes all attributes to a file.
Notes for C Programming for MCA, BCA, B. Tech CSE, ECE and MSC (CS) 5 of 5 by...ssuserd6b1fd
C programming language notes for beginners and Collage students. Written for beginners. Colored graphics. Function by Function explanation with complete examples. Well commented examples. Illustrations are made available for data dealing at memory level.
The document discusses file input/output in C++. It covers the header file fstream.h, stream classes like ifstream and ofstream for file input/output, opening and closing files, reading/writing characters and objects to files, detecting end of file, moving file pointers for random access, and handling errors. Functions like open(), close(), get(), put(), read(), write(), seekg(), seekp(), tellg(), tellp(), eof(), fail(), bad(), good(), and clear() are described.
The document discusses file input/output in C++. It covers the header file fstream.h, stream classes like ifstream and ofstream for file input/output, opening and closing files, reading/writing characters and objects to files, detecting end of file, moving file pointers for random access, and handling errors. Functions like open(), close(), get(), put(), read(), write(), seekg(), seekp(), tellg(), tellp(), eof(), fail(), bad(), good(), and clear() are described.
The document discusses files and streams in C++. It defines files as sequences of bytes that end with an end-of-file marker. Streams are used to connect programs to files for input and output. There are standard input and output streams (cin and cout) as well as file streams that use classes like ifstream for input and ofstream for output. Files can be accessed sequentially or randomly - sequential files are read from start to finish while random access files allow direct access to any record.
File handling in C++ allows programs to store data permanently by writing to files on the hard disk. The key steps are to name and create a file, open it, write data to or read from the file, then close it. Streams are used for input/output and there are stream classes like ifstream and ofstream for file operations. Exception handling uses try, catch, and throw keywords to handle runtime errors gracefully. User-defined exceptions can also be created by inheriting from the standard exception class.
The document discusses various concepts related to arrays, structures, strings, file handling, and command line arguments in C/C++. It defines arrays as a consecutive group of memory locations to store elements of the same data type. Structures are used to group related data of different types. Strings are stored as character arrays ending with a null character. File handling functions like fopen, fclose, fprintf and fscanf are used to open, close and read/write files. Command line arguments can be accessed through the argc and argv parameters in main().
The document discusses various concepts related to arrays, structures, strings, file handling, and command line arguments in C/C++. It defines arrays as a consecutive group of memory locations to store elements of the same data type. Structures are used to group related data of different types. Strings are stored as character arrays ending with a null character. File handling functions like fopen, fclose, fprintf and fscanf are used to open, close and read/write files. Command line arguments can be accessed using argc and argv array in main function.
The document discusses various topics related to structures and unions, files, and error handling in C programming. It includes:
1) Defining structures and unions, passing structures to functions, self-referential structures.
2) Opening, reading, writing, and closing files. Functions for file input/output like fopen, fprintf, fscanf, getc, putc.
3) Error handling functions like feof() and ferror() to check for end of file or errors during file operations.
This document discusses working with files in C++. It covers opening and closing files using constructors and the open() function. It describes using input and output streams to read from and write to files. It also discusses the different file stream classes like ifstream, ofstream, and fstream and their functions. Finally, it mentions the different file opening modes that can be used with the open() function.
This document discusses C++ files and streams. It covers reading and writing both sequential and random access files in C++. Some key points covered include:
- C++ views files as sequences of bytes with an end-of-file marker
- Streams are used to perform file I/O and are associated with file objects
- Sequential files are read or written to in a linear fashion while random access files allow direct access to records
- Functions like read(), write(), seekg(), seekp() are used to read from and write to files at specific positions.
The document describes an online student management system implemented using C++ that allows storing student data in a text file database. The system provides different views of the data for users like students, faculty, proctors and administrators. It allows adding, editing and viewing student details like registration number, name, marks in subjects and proctor ID. The source code implements the various user interfaces and file handling for performing CRUD operations on the text file database according to the user type.
The document discusses various ways of interacting with hardware and low-level operations in C programming. It covers opening files, reading and writing files, modifying files, calling BIOS and DOS routines, manipulating CPU registers, and interacting directly with hardware through standard library functions. Examples are provided for copying files, positioning the cursor, clearing the screen, deleting and renaming files by calling interrupt functions. Structures and unions are also explained with examples.
#include
#include
#include
#include
#include \"textFile.hpp\"
using namespace std;
void displayHelp();
bool isInteger(const string &s);
bool askSave();
int main(int argc, const char * argv[]) {
int resultCode = 0;
// Convert to a vector.
vector args(argv, argv + argc);
// Process arguments, must be 1 argument, otherwise exit with code 1.
if (args.size() < 2) {
cout << \"Missing command line argument!\" << endl;
cout << \"Usage: ./myEditor \" << endl;
resultCode = 1;
} else {
string fileName = args[1];
textFile dataFile(fileName);
// Check if the file is ok to use, if it is, lets go.
if (!dataFile.checkFile()) {
resultCode = 2;
} else {
// We can now assume the file is good, so we can work with it.
dataFile.loadFile();
// Display some text to help the user.
displayHelp();
// Now get user input.
bool done = false;
string userInput = \"\";
while (!done) {
cout << \"> \";
getline(cin, userInput);
char cmd = tolower(userInput.c_str()[0]);
char cmd2 = \' \';
if (userInput.size() > 1) {
cmd2 = userInput.c_str()[1];
}
// This check makes sure the command format is correct
// so that commands don\'t fire off by mistake.
if (strncmp(&cmd, \" \", 1) != 0 && strncmp(&cmd2, \" \", 1) == 0) {
switch(cmd) {
case \'q\': {
done = true;
break;
}
case \'i\': {
unsigned long lineIndex = dataFile.textLines() + 1;
string newLine;
if (userInput.size() > 1) {
string cmdArg = userInput.substr(2);
lineIndex = stol(cmdArg);
}
cout << to_string(lineIndex) << \"> \";
getline(cin, newLine);
dataFile.insertLine(lineIndex - 1, newLine);
break;
}
case \'d\': {
if (userInput.size() > 1) {
unsigned long lineIndex;
string cmdArg = userInput.substr(2);
lineIndex = stol(cmdArg);
dataFile.removeLine(lineIndex - 1);
}
break;
}
case \'l\': {
for (int x = 0; x < dataFile.textLines(); x++) {
cout << to_string(x + 1) << \"> \" << dataFile.getLine(x) << endl;
}
break;
}
case \'h\': {
displayHelp();
break;
}
case \'s\': {
dataFile.saveFile();
break;
}
}
}
}
// Ask about saving the file before exiting.
bool save = askSave();
if (save) {
dataFile.saveFile();
}
cout << \"Thank you for using myEditor.\" << endl;
}
}
return resultCode;
}
/*
Asks the user if they\'d like to save or not, returns true if they do. Anything
other than \"y\" or \"Y\" will be interpreted as a negative answer.
*/
bool askSave()
{
bool result = false;
string userInput = \"\";
cout << \"Do you wan to save the change? (Y - yes; N - no) \";
getline(cin, userInput);
userInput = tolower(*userInput.c_str());
if (strncmp(userInput.c_str(), \"y\", 1) == 0) {
result = true;
}
return result;
}
/*
Displays help text.
*/
void displayHelp()
{
cout << \"Welcome to my text editor.\" << endl;
cout << \"\\tTo insert text at the end of the file, type \'I\'\" << endl;
cout << \"followed by the text.\" << endl;
cout << \"\\tTo insert text at a certain line number, type \'I\'\" << endl;
cout << \"followed by a space and the desired line number.\" << endl;
cout << \"\\tTo delete a line, type \'D\' followed by a space and the\" << endl;
cou.
Basic file operations in C++ involve opening, reading from, and writing to files. The key classes for input/output with files are ofstream for writing, ifstream for reading, and fstream for both reading and writing. A file must first be opened before performing any operations on it. Common operations include writing data to files with put() or write(), reading data from files with get() or read(), and closing files after completion. Proper opening modes and error handling should be used to ensure successful file input/output.
Managing console i/o operation,working with filesramya marichamy
This document discusses C++ stream classes and file input/output. It covers the key stream classes like istream, ostream and iostream. It describes how to use stream manipulators and member functions to format console I/O. It also covers file streams like ifstream, ofstream and fstream for reading from and writing to files. Functions like open(), get(), put(), read(), write() are described for file I/O operations. Common file I/O tasks like displaying, modifying and deleting file contents are mentioned.
This document discusses C++ stream classes and file input/output. It covers the key stream classes like iostream, istream, ostream and their functions. It also discusses file classes like ifstream, ofstream and fstream that are used for file input/output. It provides examples of reading from and writing to files using these classes and their functions like open(), get(), put() etc. It mentions how file pointers are used to manipulate file positions for input/output operations.
The document discusses C++ file input/output (I/O) using fstream header file. It provides examples of writing data to a file using ofstream, reading data from a file using ifstream, and reading/writing a struct to a file. The examples demonstrate opening, reading, writing and closing files, as well as using functions to read and write data. The last example adds an expire attribute to the struct and reads/writes all attributes to a file.
Notes for C Programming for MCA, BCA, B. Tech CSE, ECE and MSC (CS) 5 of 5 by...ssuserd6b1fd
C programming language notes for beginners and Collage students. Written for beginners. Colored graphics. Function by Function explanation with complete examples. Well commented examples. Illustrations are made available for data dealing at memory level.
The document discusses file input/output in C++. It covers the header file fstream.h, stream classes like ifstream and ofstream for file input/output, opening and closing files, reading/writing characters and objects to files, detecting end of file, moving file pointers for random access, and handling errors. Functions like open(), close(), get(), put(), read(), write(), seekg(), seekp(), tellg(), tellp(), eof(), fail(), bad(), good(), and clear() are described.
The document discusses file input/output in C++. It covers the header file fstream.h, stream classes like ifstream and ofstream for file input/output, opening and closing files, reading/writing characters and objects to files, detecting end of file, moving file pointers for random access, and handling errors. Functions like open(), close(), get(), put(), read(), write(), seekg(), seekp(), tellg(), tellp(), eof(), fail(), bad(), good(), and clear() are described.
The document discusses files and streams in C++. It defines files as sequences of bytes that end with an end-of-file marker. Streams are used to connect programs to files for input and output. There are standard input and output streams (cin and cout) as well as file streams that use classes like ifstream for input and ofstream for output. Files can be accessed sequentially or randomly - sequential files are read from start to finish while random access files allow direct access to any record.
File handling in C++ allows programs to store data permanently by writing to files on the hard disk. The key steps are to name and create a file, open it, write data to or read from the file, then close it. Streams are used for input/output and there are stream classes like ifstream and ofstream for file operations. Exception handling uses try, catch, and throw keywords to handle runtime errors gracefully. User-defined exceptions can also be created by inheriting from the standard exception class.
The document discusses various concepts related to arrays, structures, strings, file handling, and command line arguments in C/C++. It defines arrays as a consecutive group of memory locations to store elements of the same data type. Structures are used to group related data of different types. Strings are stored as character arrays ending with a null character. File handling functions like fopen, fclose, fprintf and fscanf are used to open, close and read/write files. Command line arguments can be accessed through the argc and argv parameters in main().
The document discusses various concepts related to arrays, structures, strings, file handling, and command line arguments in C/C++. It defines arrays as a consecutive group of memory locations to store elements of the same data type. Structures are used to group related data of different types. Strings are stored as character arrays ending with a null character. File handling functions like fopen, fclose, fprintf and fscanf are used to open, close and read/write files. Command line arguments can be accessed using argc and argv array in main function.
The document discusses various topics related to structures and unions, files, and error handling in C programming. It includes:
1) Defining structures and unions, passing structures to functions, self-referential structures.
2) Opening, reading, writing, and closing files. Functions for file input/output like fopen, fprintf, fscanf, getc, putc.
3) Error handling functions like feof() and ferror() to check for end of file or errors during file operations.
Odoo 18 Point of Sale PWA - Odoo SlidesCeline George
Progressive Web Apps (PWA) are web applications that deliver an app-like experience using modern web technologies, offering features like offline functionality, installability, and responsiveness across devices.
This study describe how to write the Research Paper and its related issues. It also presents the major sections of Research Paper and various tools & techniques used for Polishing Research Paper
before final submission.
Finding a Right Journal and Publication Ethics are explain in brief.
"Orthoptera: Grasshoppers, Crickets, and Katydids pptxArshad Shaikh
Orthoptera is an order of insects that includes grasshoppers, crickets, and katydids. Characterized by their powerful hind legs, Orthoptera are known for their impressive jumping ability. With diverse species, they inhabit various environments, playing important roles in ecosystems as herbivores and prey. Their sounds, often produced through stridulation, are distinctive features of many species.
Research Handbook On Environment And Investment Law Kate Milesmucomousamir
Research Handbook On Environment And Investment Law Kate Miles
Research Handbook On Environment And Investment Law Kate Miles
Research Handbook On Environment And Investment Law Kate Miles
Principal Satbir Singh writes “Kaba and Kitab i.e. Building Harmandir Sahib and Compilation of Granth Sahib gave Sikhs a central place of worship and a Holy book is the single most important reason for Sikhism to flourish as a new religion which gave them a identity which was separate from Hindu’s and Muslim’s.
Protest - Student Revision Booklet For VCE Englishjpinnuck
The 'Protest Student Revision Booklet' is a comprehensive resource to scaffold students to prepare for writing about this idea framework on a SAC or for the exam. This resource helps students breakdown the big idea of protest, practise writing in different styles, brainstorm ideas in response to different stimuli and develop a bank of creative ideas.
"Dictyoptera: The Order of Cockroaches and Mantises" Or, more specifically: ...Arshad Shaikh
Dictyoptera is an order of insects that includes cockroaches and praying mantises. These insects are characterized by their flat, oval-shaped bodies and unique features such as modified forelegs in mantises for predation. They inhabit diverse environments worldwide.
This article explores the miraculous event of the Splitting of the Moon (Shaqq al-Qamar) as recorded in Islamic scripture and tradition. Drawing from the Qur'an, authentic hadith collections, and classical tafsir, the article affirms the event as a literal miracle performed by Prophet Muhammad ﷺ in response to the Quraysh’s demand for a sign. It also investigates external historical accounts, particularly the legend of Cheraman Perumal, a South Indian king who allegedly witnessed the miracle and embraced Islam. The article critically examines the authenticity and impact of such regional traditions, while also discussing the lack of parallel astronomical records and how scholars have interpreted this event across centuries. Concluding with the theological significance of the miracle, the article offers a well-rounded view of one of Islam’s most discussed supernatural events.
CURRENT CASE COUNT: 880
• Texas: 729 (+5) (56% of cases are in Gaines County)
• New Mexico: 78 (+4) (83% of cases are from Lea County)
• Oklahoma: 17
• Kansas: 56 (38.89% of the cases are from Gray County)
HOSPITALIZATIONS: 103
• Texas: 94 - This accounts for 13% of all cases in the State.
• New Mexico: 7 – This accounts for 9.47% of all cases in New Mexico.
• Kansas: 2 - This accounts for 3.7% of all cases in Kansas.
DEATHS: 3
• Texas: 2 – This is 0.28% of all cases
• New Mexico: 1 – This is 1.35% of all cases
US NATIONAL CASE COUNT: 1,076 (confirmed and suspected)
INTERNATIONAL SPREAD
• Mexico: 1,753 (+198) 4 fatalities
‒ Chihuahua, Mexico: 1,657 (+167) cases, 3 fatalities, 9 hospitalizations
• Canada: 2518 (+239) (Includes Ontario’s outbreak, which began November 2024)
‒ Ontario, Canada: 1,795 (+173) 129 (+10) hospitalizations
‒ Alberta, Canada: 560 (+55)
Things to keep an eye on:
Mexico: Three children have died this month (all linked to the Chihuahua outbreak):
An 11-month-old and a 7-year-old with underlying conditions
A 1-year-old in Sonora whose family is from Chihuahua
Canada:
Ontario now reports more cases than the entire U.S.
Alberta’s case count continues to climb rapidly and is quickly closing in on 600 cases.
Emerging transmission chains in Manitoba and Saskatchewan underscore the need for vigilant monitoring of under-immunized communities and potential cross-provincial spread.
United States:
North Dakota: Grand Forks County has confirmed its first cases (2), linked to international travel. The state total is 21 since May 2 (including 4 in Cass County and 2 in Williams County), with one hospitalization reported.
OUTLOOK: With the spring–summer travel season peaking between Memorial Day and Labor Day, both domestic and international travel may fuel additional importations and spread. Although measles transmission is not strictly seasonal, crowded travel settings increase the risk for under-immunized individuals.
File Handling in C++ full ppt slide presentation.ppt
1. Disk File I/O in
C++
Dr. Syed Aun Irtaza
Department of Computer Science
University of Engineering and Technology
(UET) Taxila
2. Disk File I/O with Streams
O Working with disk files requires set of classes:
O ifstream for input,
O ofstream for output.
O fstream for both input and output
O Objects of these classes can be associated with disk
files, and we can use their member functions to read
and write to the files.
O The ifstream, ofstream, and fstream classes are
declared in the FSTREAM file.
4. Writing Data formatted I/O,
int main() {
char ch = ‘x’;
int j = 77;
double d = 6.02;
string str1 = “Hello”;
string str2 = “Testing”;
ofstream outfile(“data.txt”); //create ofstream object
outfile << ch << j << ‘ ‘ << d << str1 << ‘ ‘ << str2;
cout << “File writtenn”;
return 0;
}
If the file doesn’t exist,
it is created.
If it does exist, it is
truncated and the new
data replaces the old.
6. Strings with Embedded Blanks
#include <fstream>
int main() {
ofstream
outfile(“TEST.TXT”);
outfile << “Hello Dear !n”;
outfile << “We are writingn”;
outfile << “data in filesn”;
outfile << “with
embeddedn”;
outfile << “blanksn”;
return 0;
}
#include <iostream>
#include<fstream>
int main() {
const int MAX = 80;
char buffer[MAX];
ifstream infile(“TEST.TXT”);
while( !infile.eof() ) {
infile.getline(buffer, MAX);
cout << buffer << endl;
}
return 0;
}
7. Character I/O
#include <fstream>
#include <iostream>
#include <string>
int main() {
string str = “Time is a great teacher, but
unfortunately it
kills all its pupils. Berlioz”;
ofstream outfile(“TEST.TXT”);
for(int j=0; j<str.size(); j++)
outfile.put( str[j] );
cout << “File writtenn”;
return 0;
}
8. Character I/O
#include <fstream>
#include <iostream>
void main() {
char ch;
ifstream infile(“TEST.TXT”);
while( infile ){
infile.get(ch); //read character
cout << ch; //display it
}
cout << endl;
}
read until EOF or error
9. Binary I/O
O We can write a few numbers to disk using
formatted I/O, but if you’re storing a large
amount of numerical data it’s more
efficient to use binary I/O
O In binary I/O numbers are stored as they
are in the computer’s RAM memory,
rather than as strings of characters
10. Binary I/O
O In binary I/O an int is stored in 4 bytes,
whereas its text version might be “12345”,
requiring 5 bytes.
O Similarly, a float is always stored in 4
bytes, while its formatted version might be
“6.02314e13”, requiring 10 bytes.
11. Reading & Writing an Object to Disk
struct student{
int rno;
char name[25];
};
void getdata(student &s1){
cout<<"nEnter name";cin>>s1.name;
cout<<"nEnter Roll no";cin>>s1.rno;
}
void showdata(student &s2){
cout<<"nName";cout<<s2.name;
cout<<"nRoll no"<<s2.rno;
}
12. Reading & Writing an Object to Disk
int main() {
student std[3];
for(int i=0; i<=2; i++)
getdata(std[i]);
ofstream outfile("std.txt", ios::binary);
for(int a=0; a<=2; a++)
outfile.write(reinterpret_cast<char*>(&std[a]), sizeof(std[a]));
ifstream infile("std.txt", ios::binary);
for(int a=0; a<=2; a++){
infile.read( reinterpret_cast<char*>(&std[a]), sizeof(std[a]));
showdata(std[a]);
}
}
14. File pointer positions
O Each file object has associated with it two integer values
called the get pointer and the put pointer.
O These are also called the current get position and the current
put position.
O These values specify the byte number in the file where
writing or reading will take place.
O The seekg() and tellg() functions allow you to set and
examine the get pointer.
O The seekp() and tellp() functions perform these same
actions on the put pointer.
15. File pointer positions
O For example, will set the put pointer to 10 bytes
before the end of the file.
O seekp(-10, ios::end);
O For example, will set the put pointer to the end of
file.
O infile.seekg(0, ios::end);