C++ File Input/Output Fundamentals

ece 244 n.w
1 / 9
Embed
Share

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++.

  • C++
  • File IO
  • Input Output
  • Programming

Uploaded on | 0 Views


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


  1. ECE 244 Programming Fundamentals Lec. 5: C++ I/O Ding Yuan ECE Dept., University of Toronto http://www.eecg.toronto.edu/~yuan

  2. Standard input/output #include <iostream> using namespace std; int main() { int x; cout<< Hello world! << endl; cin >> x; } output input Hello world!

  3. File input/output program file file

  4. 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

  5. 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

  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

  7. 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?

  8. You open, you close! When done reading/writing to a file, close it! inFile.close(); outFile.close();

  9. 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

Related


More Related Content