Lecture 6
File I/O in C++
Using Input / Output Files
A computer file
is stored on a secondary storage device (e.g., disk);
is permanent;
can be used to
provide input data to a program
or receive output data from a program
or both;
should reside in Project directory for easy access;
must be opened before it is used.
General File I/O Steps
1. Include the header file fstream in the program.
2. Declare file stream variables.
3. Associate the file stream variables with the
input/output files by opening the file.
4. Use the file stream variables with >>, <<, or
other input/output functions.
5. Close the file.
Streams
stream - a sequence of characters
interactive (iostream)
•
•
•
• cin - input stream associated with
keyboard.
• cout - output stream associated with
display
file (fstream)
•
•
•
• ifstream - defines new input stream
(normally associated with a file).
•
•
•
• ofstream - defines new output stream
(normally associated with a file).
Streams
Stream I/O Library Header Files
Note: There is no “.h” on standard header files : <fstream>
iostream -- contains basic information required for all
stream I/O operations
fstream -- contains information for performing file I/O
operations
File Stream Objects
• There are three types of file stream
objects
(1) ifstream objects: used for input
(2) ofstream objects: used for output
(3) fstream objects: used for both
input and output
13-7
C++ streams
Open() Function
Opening a file associates a file stream variable declared
in the program with a physical file at the source, such
as a disk.
In the case of an input file:
the file must exist before the open statement executes.
If the file does not exist, the open statement fails and the
input stream enters the fail state
An output file does not have to exist before it is
opened;
if the output file does not exist, the computer prepares an
empty file for output.
If the designated output file already exists, by default, the
old contents are erased when the file is opened.
input_stream.open("numbers.txt“)
Open() Function
Important File Functions
getline() - read a line of text from text file store in a string.
Syntax: getline(Input file, String, Delimiting Char);
Example: getline(ifile1, str1, ‘,’);
Example: getline(ifile1, str1);
eof() - This function determines the end-of-file by returning
true(non-zero) for end of file otherwise returning false(zero).
Example : fout.eof( );
Example1: Opening and Closing
#include <fstream>
int main ()
{
ifstream fsIn;//input
ofstream fsOut; // output
//Open the files
fsIn.open("prog1.txt"); //open the input file
fsOut.open("prog2.txt"); //open the output
//Code for data manipulation
//Close files
fsIn.close();
fsOut.close();
return 0;
}
Example2: Writing a string to a file
#include <fstream>
using namespace std;
int main()
{// declare output file variable
ofstream outFile;
// open an exist file fout.txt
outFile.open("fout.txt”);
//behave just like cout, put the word into the file
outFile << "Hello World!";
// Closing the file
outFile.close();
return 0;
}
Example3: Reading from a file -p1
// reading a text file
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main()
{
string line1;
ifstream myfile;
myfile.open("example.txt");
if (myfile.is_open())
{
while (getline(myfile, line1))
{
cout << line1 << 'n';
}
myfile.close();
}
else cout << "Unable to open file"<< endl;
system("pause");
return 0;
}
Example3: Reading from a file –p2
CSV Files
A Comma Separated Values (CSV) file is a plain
text file that contains a list of data. These files
are often used for exchanging data between
different applications. For example, databases
and contact managers often support CSV files.
These files may sometimes be called Character
Separated Values or Comma Delimited files.
They mostly use the comma character to
separate (or delimit) data.
The Structure of a CSV File
A CSV file has a fairly simple structure. It’s a list
of data separated by commas.
You can open CSV file in Notepad or Excel
Name,Email,Phone Number,Address
Bob Smith,bob@example.com,123-456-7890,123 SF
Mike Jones,mike@example.com,098-765-4321,321 LA
Ex 4: Reading CSV into an Array p1
// reading a text file
// You need to include the below files
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main()
{
// Define Stage
string line1;
ifstream myfile;
string Info[3][4];
// Opening the file
myfile.open("test1.csv");
if (myfile.is_open())
{
for (int i = 0; i < 3; i++)
{
for (int j = 0; j < 4; j++)
{
while (getline(myfile, line1,','))
{
cout << line1 << 'n';//show to user
Info[i][j] = line1;//store in Array
}
}
}
myfile.close();
}
Ex 4: Reading CSV into an Array p2
else cout << "Unable to open file"<< endl;
system("pause");
return 0;
}
Ex 4: Reading CSV into an Array p3
// Writing Array to CSv file
//Include below files
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main()
{
// Define Stage
int i, j;
ofstream myfile;
string Info[100][4];
Ex 5: Writing Array to CSV file p1
//Input the information from the user
for (int i = 0; i < 100; i++)
{
for (int j = 0; j < 4; j++)
{
cin >> Info[i][j]; // store the user input in the array
}
}
//Output the information to the file
// First open the file
myfile.open("test1.csv");
Ex 5: Writing Array to CSV file p2
Ex 5: Writing Array to CSV file p3
if (myfile.is_open())
{
for (int i = 0; i < 100; i++)
{
for (int j = 0; j < 4; j++)
{
myfile << Info[i][j] << ','; // store the data to file
}
myfile << endl; // shift to new line
}
myfile.close();
}
else cout << "Unable to open file"<< endl;
system("pause");
return 0;
}
Ex 6: Passing File Stream Objects to
Functions
//print all integers in a file to screen
void printFile(ifstream &file1)
{
int x;
while(getline(file1,x))
{
cout << x << " ";
}
}
13-24

More Related Content

PPT
csc1201_lecture13.ppt
PPTX
file.pptx 43dcsddsafgdewdvvbghghsdwweffr
PPTX
Basics of file handling
PPTX
basics of file handling
PPTX
Introduction to files management systems
PPTX
Cs1123 10 file operations
PPTX
File management in C++
PPT
new pdfrdfzdfzdzzzzzzzzzzzzzzzzzzzzzzzzzzgggggggggggggggggggggggggggggggggggg...
csc1201_lecture13.ppt
file.pptx 43dcsddsafgdewdvvbghghsdwweffr
Basics of file handling
basics of file handling
Introduction to files management systems
Cs1123 10 file operations
File management in C++
new pdfrdfzdfzdzzzzzzzzzzzzzzzzzzzzzzzzzzgggggggggggggggggggggggggggggggggggg...

Similar to DOC-20241121-WA0004bwushshusjssjuwh..pdf (20)

PPT
file_handling_in_c.ppt
PPTX
Data file handling
PPTX
Programming in C Session 4
PPT
7 Data File Handling
PPTX
File handling in C
PDF
Filesinc 130512002619-phpapp01
PPSX
Files in c++
PPTX
MODULE 8-File and preprocessor.pptx for c program learners easy learning
PPT
File handling in C++
PDF
EASY UNDERSTANDING OF FILES IN C LANGUAGE.pdf
PPTX
File management
PPT
17 files and streams
PDF
File handling
PPT
Data file handling
PPTX
Chapter4.pptx
PPT
File in cpp 2016
PPTX
working with files
PDF
VIT351 Software Development VI Unit5
PPTX
RECAPITULATION pythom numpy DAY - 5.pptx
PDF
Files in C++.pdf is the notes of cpp for reference
file_handling_in_c.ppt
Data file handling
Programming in C Session 4
7 Data File Handling
File handling in C
Filesinc 130512002619-phpapp01
Files in c++
MODULE 8-File and preprocessor.pptx for c program learners easy learning
File handling in C++
EASY UNDERSTANDING OF FILES IN C LANGUAGE.pdf
File management
17 files and streams
File handling
Data file handling
Chapter4.pptx
File in cpp 2016
working with files
VIT351 Software Development VI Unit5
RECAPITULATION pythom numpy DAY - 5.pptx
Files in C++.pdf is the notes of cpp for reference
Ad

Recently uploaded (20)

PPTX
1.Introduction to orthodonti hhhgghhcs.pptx
PPT
Technicalities in writing workshops indigenous language
PPTX
transformers as a tool for understanding advance algorithms in deep learning
PPT
What is life? We never know the answer exactly
PPTX
inbound6529290805104538764.pptxmmmmmmmmm
PPT
BME 301 Lecture Note 1_2.ppt mata kuliah Instrumentasi
PPTX
Basic Statistical Analysis for experimental data.pptx
PPT
2011 HCRP presentation-final.pptjrirrififfi
PDF
toaz.info-grade-11-2nd-quarter-earth-and-life-science-pr_5360bfd5a497b75f7ae4...
PDF
General category merit rank list for neet pg
PDF
Mcdonald's : a half century growth . pdf
PDF
Nucleic-Acids_-Structure-Typ...-1.pdf 011
PDF
Delhi c@ll girl# cute girls in delhi with travel girls in delhi call now
PPTX
DIGITAL DESIGN AND.pptx hhhhhhhhhhhhhhhhh
PDF
NU-MEP-Standards معايير تصميم جامعية .pdf
PDF
Book Trusted Companions in Delhi – 24/7 Available Delhi Personal Meeting Ser...
PPTX
Stats annual compiled ipd opd ot br 2024
PPTX
Sheep Seg. Marketing Plan_C2 2025 (1).pptx
PPTX
ch20 Database System Architecture by Rizvee
PPTX
GPS sensor used agriculture land for automation
1.Introduction to orthodonti hhhgghhcs.pptx
Technicalities in writing workshops indigenous language
transformers as a tool for understanding advance algorithms in deep learning
What is life? We never know the answer exactly
inbound6529290805104538764.pptxmmmmmmmmm
BME 301 Lecture Note 1_2.ppt mata kuliah Instrumentasi
Basic Statistical Analysis for experimental data.pptx
2011 HCRP presentation-final.pptjrirrififfi
toaz.info-grade-11-2nd-quarter-earth-and-life-science-pr_5360bfd5a497b75f7ae4...
General category merit rank list for neet pg
Mcdonald's : a half century growth . pdf
Nucleic-Acids_-Structure-Typ...-1.pdf 011
Delhi c@ll girl# cute girls in delhi with travel girls in delhi call now
DIGITAL DESIGN AND.pptx hhhhhhhhhhhhhhhhh
NU-MEP-Standards معايير تصميم جامعية .pdf
Book Trusted Companions in Delhi – 24/7 Available Delhi Personal Meeting Ser...
Stats annual compiled ipd opd ot br 2024
Sheep Seg. Marketing Plan_C2 2025 (1).pptx
ch20 Database System Architecture by Rizvee
GPS sensor used agriculture land for automation
Ad

DOC-20241121-WA0004bwushshusjssjuwh..pdf

  • 2. Using Input / Output Files A computer file is stored on a secondary storage device (e.g., disk); is permanent; can be used to provide input data to a program or receive output data from a program or both; should reside in Project directory for easy access; must be opened before it is used.
  • 3. General File I/O Steps 1. Include the header file fstream in the program. 2. Declare file stream variables. 3. Associate the file stream variables with the input/output files by opening the file. 4. Use the file stream variables with >>, <<, or other input/output functions. 5. Close the file.
  • 4. Streams stream - a sequence of characters interactive (iostream) • • • • cin - input stream associated with keyboard. • cout - output stream associated with display file (fstream) • • • • ifstream - defines new input stream (normally associated with a file). • • • • ofstream - defines new output stream (normally associated with a file).
  • 6. Stream I/O Library Header Files Note: There is no “.h” on standard header files : <fstream> iostream -- contains basic information required for all stream I/O operations fstream -- contains information for performing file I/O operations
  • 7. File Stream Objects • There are three types of file stream objects (1) ifstream objects: used for input (2) ofstream objects: used for output (3) fstream objects: used for both input and output 13-7
  • 9. Open() Function Opening a file associates a file stream variable declared in the program with a physical file at the source, such as a disk. In the case of an input file: the file must exist before the open statement executes. If the file does not exist, the open statement fails and the input stream enters the fail state An output file does not have to exist before it is opened; if the output file does not exist, the computer prepares an empty file for output. If the designated output file already exists, by default, the old contents are erased when the file is opened.
  • 11. Important File Functions getline() - read a line of text from text file store in a string. Syntax: getline(Input file, String, Delimiting Char); Example: getline(ifile1, str1, ‘,’); Example: getline(ifile1, str1); eof() - This function determines the end-of-file by returning true(non-zero) for end of file otherwise returning false(zero). Example : fout.eof( );
  • 12. Example1: Opening and Closing #include <fstream> int main () { ifstream fsIn;//input ofstream fsOut; // output //Open the files fsIn.open("prog1.txt"); //open the input file fsOut.open("prog2.txt"); //open the output //Code for data manipulation //Close files fsIn.close(); fsOut.close(); return 0; }
  • 13. Example2: Writing a string to a file #include <fstream> using namespace std; int main() {// declare output file variable ofstream outFile; // open an exist file fout.txt outFile.open("fout.txt”); //behave just like cout, put the word into the file outFile << "Hello World!"; // Closing the file outFile.close(); return 0; }
  • 14. Example3: Reading from a file -p1 // reading a text file #include <iostream> #include <fstream> #include <string> using namespace std; int main() { string line1; ifstream myfile; myfile.open("example.txt");
  • 15. if (myfile.is_open()) { while (getline(myfile, line1)) { cout << line1 << 'n'; } myfile.close(); } else cout << "Unable to open file"<< endl; system("pause"); return 0; } Example3: Reading from a file –p2
  • 16. CSV Files A Comma Separated Values (CSV) file is a plain text file that contains a list of data. These files are often used for exchanging data between different applications. For example, databases and contact managers often support CSV files. These files may sometimes be called Character Separated Values or Comma Delimited files. They mostly use the comma character to separate (or delimit) data.
  • 17. The Structure of a CSV File A CSV file has a fairly simple structure. It’s a list of data separated by commas. You can open CSV file in Notepad or Excel Name,Email,Phone Number,Address Bob Smith,[email protected],123-456-7890,123 SF Mike Jones,[email protected],098-765-4321,321 LA
  • 18. Ex 4: Reading CSV into an Array p1 // reading a text file // You need to include the below files #include <iostream> #include <fstream> #include <string> using namespace std; int main() { // Define Stage string line1; ifstream myfile; string Info[3][4]; // Opening the file myfile.open("test1.csv");
  • 19. if (myfile.is_open()) { for (int i = 0; i < 3; i++) { for (int j = 0; j < 4; j++) { while (getline(myfile, line1,',')) { cout << line1 << 'n';//show to user Info[i][j] = line1;//store in Array } } } myfile.close(); } Ex 4: Reading CSV into an Array p2
  • 20. else cout << "Unable to open file"<< endl; system("pause"); return 0; } Ex 4: Reading CSV into an Array p3
  • 21. // Writing Array to CSv file //Include below files #include <iostream> #include <fstream> #include <string> using namespace std; int main() { // Define Stage int i, j; ofstream myfile; string Info[100][4]; Ex 5: Writing Array to CSV file p1
  • 22. //Input the information from the user for (int i = 0; i < 100; i++) { for (int j = 0; j < 4; j++) { cin >> Info[i][j]; // store the user input in the array } } //Output the information to the file // First open the file myfile.open("test1.csv"); Ex 5: Writing Array to CSV file p2
  • 23. Ex 5: Writing Array to CSV file p3 if (myfile.is_open()) { for (int i = 0; i < 100; i++) { for (int j = 0; j < 4; j++) { myfile << Info[i][j] << ','; // store the data to file } myfile << endl; // shift to new line } myfile.close(); } else cout << "Unable to open file"<< endl; system("pause"); return 0; }
  • 24. Ex 6: Passing File Stream Objects to Functions //print all integers in a file to screen void printFile(ifstream &file1) { int x; while(getline(file1,x)) { cout << x << " "; } } 13-24