
C++ File Input/Output Fundamentals
Learn about file input and output operations in C++, including standard input/output, file open modes, buffering, and best practices for handling file operations. Understand how to read from and write to files using ifstream, ofstream, and fstream classes in C++.
Download Presentation

Please find below an Image/Link to download the presentation.
The content on the website is provided AS IS for your information and personal use only. It may not be sold, licensed, or shared on other websites without obtaining consent from the author. If you encounter any issues during the download, it is possible that the publisher has removed the file from their server.
You are allowed to download the files provided on this website for personal or commercial use, subject to the condition that they are used lawfully. All files are the property of their respective owners.
The content on the website is provided AS IS for your information and personal use only. It may not be sold, licensed, or shared on other websites without obtaining consent from the author.
E N D
Presentation Transcript
ECE 244 Programming Fundamentals Lec. 5: C++ I/O Ding Yuan ECE Dept., University of Toronto http://www.eecg.toronto.edu/~yuan
Standard input/output #include <iostream> using namespace std; int main() { int x; cout<< Hello world! << endl; cin >> x; } output input Hello world!
File input/output program file file
File input #include <fstream> using namespace std; ifstream inFile( filename ); or ifstream inFile; inFile.open ( filename ); a = 1 b = 2 c = 3 int a,b,c; inFile >> a >> b >> c; 1 2 3 if in ifstream stands for input and file
File output #include <fstream> using namespace std; ofstream outFile( filename ); or ofstream outFile; outFile.open ( filename ); int a = 6; outFile << a = << a << endl; a = 6
Two ways to open a file for output Open for writing (default) If the file already exists, it is first erased; Otherwise it is created Open for append Use: outFile.open( filename , ios::app); Write adds to the end of the file
When opening file inFile.open ( filename ); <- search in current directory inFile.open ( dir/filename ); <- relative path inFile.open ( ../filename ); <- relative path inFile.open ( /etc/passwd ); <- absolute path Question: why do we need to open a file?
You open, you close! When done reading/writing to a file, close it! inFile.close(); outFile.close();
Buffering Output will not be immediately written to file Instead, temporarily store the output in buffer; write out to file periodically in chunks Why buffering? To force output: outFile.flush(); or outFile << endl; outFile << Hello \n ; .. outFile << Hello again! ; Buffer: Hello Hello again! Slow! file