LAB11OOP

Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 17

PLO4/ CLO3 PLO10/ PLO8/ PLO9/

CLO4 CLO5 CLO6

Analysis
of data
in Lab Modern Ethics Individua
Report Tool and l and
Viva / Usage Safety Teamwor
Quiz / Lab k
Name Reg. No Performanc
e

5 Marks 5 Marks 5 5 Marks 5 Marks


Marks

Eman Razi 475146


Department of Electrical Engineering

Dated: December 3, 2024 Semester: 3rd

Section: BEE-15(D) Lab Engineer: Engr. Syed Zain Ul Hassan

CS-212 OBJECT ORIENTED PROGRAMMING

LAB 11: File Handling

1
2
EXPERIMENT NO 11

File Handling in c++

Objectives:
 To learn about handling file in C++, reading and writing to
a file.
Equipment required:
 Visual Studio/ Dev C+
+

Description:
When a program needs to save data for later use, it writes the data in a
file. The data can then be read from the file at a later time.
If a program is to retain data between the times it runs, it must have a
way of saving it. Data is saved in a file, which is usually stored on a
computer’s disk.
Commercial software that you use on a day-to-day basis store data in files .
1)Word processors:
Word processing programs are used to write letters, memos, documents.
reports,and other The documents are then saved in files so
they can be edited and printed.
Image editors: Images
Spreadsheets: Num data
Games: User info
Web browsers: Cookies

Type of file:
In general, there are two types of files: text and binary
A text file contains data that has been encoded as text, using a scheme
such as ASCII or Unicode.
 Even if the file contains numbers, those numbers are stored in the
file as a series of characters.
 As a result, the file may be opened and viewed in a text editor such as
Notepad A binary file contains data that has not been converted to text.
Thus, you cannot view the contents of a binary file with a text editor

File Access method:

• There are two general ways to access data stored in a file:


3
4
5
File names and File stream objects:

Each operating system has its own rules for naming files. Many
systems, including Windows, support the use of filename extensions,
which are short sequences of
characters that apparat the end of a filename preceded by a period (known
as a “dot”).
For example, the files have the extensions .jpg, .txt, and .doc. The
extension usually indicates the type of data stored in the file.
In order for a program to work with a file on the computer’s disk, the
program must create a file stream object in memory
A file stream object is an object that is associated with a specific file and
provides a
way for the program to work with that file. It is called a “stream”
object because a file can be thought of as a stream of data
File stream objects work very much like the cin and cout objects. A
stream of data may be sent to cout, which causes values to be
displayed on the screen.
A stream of data may be read from the keyboard by cin, and stored in
variables. Likewise, streams of data may be sent to a file stream
object, which writes the data to a file.
Setting Up a Program for File Input/Output:

Just as cin and cout require the iostream file to be included in the
program, C++ file access requires another header file. The file
fstream contains all the declarations necessary for file operations
It is included with the following statement:

#include <fstream>

Creating a File Object and Opening a File:

Before data can be written to or read from a file, the following things must
happen:

1) A file stream object must be created


2) The file must be opened and linked to the file stream object

6
7
8
The following code shows an example of opening a file for input (reading).

ifstream inputFile;
inputFile.open("Customers.txt"
);

The first statement defines an ifstream object named inputFile. The


second statement calls the object’s open member function, passing
the string "Customers.txt" as an argument

The following code shows an example of opening a file for output (writing).

ofstream outputFile;
outputFile.open("Employees.txt"
);

The first statement defines an ofstream object named outputFile. The second
statement calls the object’s open member function, passing the
string "Employees.txt" as an argument. In this statement, the open
member function creates the
Employees.txt file and links it with the outputFile object.

Often, when opening a file, you will need to specify its path as well as
its name. For example, on a Windows system the following
statement opens the file
C:\data\inventory.txt:

inputFile.open("C:\\data\\inventory.txt")
In this statement, the file C:\data\inventory.txt is opened and linked with inputFile
To define a file stream object and open a file in one statement.
ifstream inputFile("Customers.txt");
ofstream outputFile("Employees.txt");

Closing a File:

The opposite of opening a file is closing it. Although a program’s files


are
automatically closed when the program shuts down, it is a good
programming practice to write statements that close them
Calling the file stream object’s close member function closes a
file. Here is an example:

inputFile.close();

9
10
Lab Tasks:

1. Open a demo file and write 5 strings in the file.

CODE:
#include <iostream>

#include <fstream>

#include <vector>

#include <string>

class FileWriter {

private:

std::string fileName; // Name of the file

std::vector<std::string> lines; // Vector to store lines

public:

// Constructor to set the file name

FileWriter(const std::string& file) : fileName(file) {}

// Method to add a line to the list

void addLine(const std::string& line) {

lines.push_back(line);

// Method to write lines to the file

void writeToFile() const {

std::ofstream outFile(fileName);

if (outFile.is_open()) {

for (const auto& line : lines) {

outFile << line << std::endl;

outFile.close();

std::cout << "Strings written to file successfully!" << std::endl;

11
} else {

std::cerr << "Failed to open file: " << fileName << std::endl;

};

int main() {

// Create an instance of FileWriter

FileWriter fileWriter("output_file.txt");

// Add lines to the FileWriter object

fileWriter.addLine("Hello, this is the first line.");

fileWriter.addLine("This is the second line of the file.");

fileWriter.addLine("Here comes the third line with some text.");

fileWriter.addLine("The fourth line is here to say hi!");

fileWriter.addLine("Finally, this is the fifth and last line.");

// Write the lines to the file

fileWriter.writeToFile();

return 0;

OUTPUT:

12
2. Open a file and write user input numbers in the file.

Code:
#include <iostream>

#include <fstream>

using namespace std;

int main() {

string fileName = "labtask02.txt"; // File name to write to

ofstream outFile(fileName); // Create an output file stream

if (!outFile) {

cout << "Error: Could not open the file." << endl;

return 1;

int numInputs;

cout << "How many numbers do you want to write to the file? ";

cin >> numInputs;

cout << "Enter " << numInputs << " numbers:" << endl;

for (int i = 0; i < numInputs; i++) {

int number;

cin >> number; // Take user input

13
outFile << number << endl; // Write the number to the file

outFile.close(); // Close the file

cout << "Numbers successfully written to " << labtask02.txt << "!" << endl;

return 0;

Output:

3. Open a file and Read Data from the file, display the contents on the console.

Code:

#include <iostream>
#include <fstream>
#include <string>
using namespace std;

14
int main() {
string fileName = "labtask02.txt"; // File name to read from
ifstream inFile(fileName); // Create an input file stream

if (!inFile) {
cerr << "Error: Could not open the file." << endl;
return 1;
}

cout << "Contents of the file '" << fileName << "':" << endl;

string line;
while (getline(inFile, line)) { // Read each line from the file
cout << line << endl; // Display the line on the console
}

inFile.close(); // Close the file


return 0;
}

Output:

4. Open a file Read numeric data from the file and display the largest number in those written
numbers
Code:
#include <iostream>
#include <fstream>
#include <limits>
using namespace std;

int main() {
string fileName = "labtask02.txt"; // Updated file name
ifstream inFile(fileName); // Create an input file stream

// Check if the file was opened successfully


if (!inFile) {
cerr << "Error: Could not open the file." << endl;

15
return 1;
}

int number;
int largest = numeric_limits<int>::min(); // Initialize to the smallest integer

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

// Read numbers from the file and find the largest


while (inFile >> number) {
if (number > largest) {
largest = number; // Update the largest number
}
}

// If no numbers were found in the file


if (largest == numeric_limits<int>::min()) {
cout << "No numbers found in the file!" << endl;
} else {
cout << "The largest number in the file is: " << largest << endl;
}

inFile.close(); // Close the file


return 0;
}
Output:

5. Use while loop to read data from file and display the contents.

Code:

#include <iostream>
#include <fstream>
#include <string>
using namespace std;

int main() {
string fileName = "labtask02.txt"; // Name of the file to read
ifstream inFile(fileName); // Open the file for reading

// Check if the file was opened successfully


if (!inFile) {
cerr << "Error: Could not open the file." << endl;
return 1;
}

16
string line;
cout << "Reading data from the file..." << endl;

// Use a while loop to read the file line by line


while (getline(inFile, line)) { // Read each line from the file
cout << line << endl; // Display the line on the console
}

inFile.close(); // Close the file after reading


return 0;
}

Output:

17

You might also like