Files and Streams

File Stream

  • iostream
    • ostream (cout)
    • istream (cin)
  • fstream
    • ofstream (file stream for writing)
    • ifstream
#include <iostream>
#include <fstream>
#include <string>

using namespace std;

int main() {

	// Open file
	ifstream input_file{"my_text.txt"};
	
	// Check for error 
	if (input_file)
		cout << "Successfull" << endl;
	else
		cout << "Failed to open file"; 


	// Read file 
	string text; 

	// //read one word at a time 
	// while (input_file >> text){
	// 	cout << text << endl;
	// }

	//read one line at a time 
	while (getline(input_file,text)){
		cout << text << endl;
	}
	// Close file
	input_file.close();
	



	// Open file
	ofstream output_file("output.txt");
	
	// Check for error 
	if (output_file)
		cout << "Successfull" << endl;
	else
		cout << "Failed to open file"; 

	// Write to file
	output_file << "Hello" << " " << "World!" << endl;

	// Close file
	output_file.close();
}

Streams and Buffering

C++’da stream’ler buffering yapar. Bunun temel amacı sistem çağrılarını minimize etmektir. Yazma operasyonlarında veri, bellekteki buffer’a yazılır. Buffer dolduğunda ise veri işletim sistemine gönderilir. Bu duruma “flushing” denilir.

Ne zaman flush yapılır?

  • input stream’ler için direk bir yolu yoktur
  • ofstream sadece buffer dolduğunda flush eder
  • ostream
    • genelde her satrıın sonunda
    • cin ile okuma yapmadan önce

manual olarak flush yapabiliriz:

cout << "Merhaba" << flush;

endl equivalent of “\n” << flush

Unbuffered Input and Output

File Modes

ios::inOpen for input operations.
ios::outOpen for output operations.
ios::binaryOpen in binary mode.
ios::ateSet the initial position at the end of the file.
If this flag is not set, the initial position is the beginning of the file.
ios::appAll output operations are performed at the end of the file, appending the content to the current content of the file.
ios::truncIf the file is opened for output operations and it already existed, its previous content is deleted and replaced by the new one.
https://cplusplus.com/doc/Tutorial/files/

Stream Member Functions and State

FlagMeaning
goodbitEverything is okay
badbitSome kind of fatal error occurred (e.g. the program tried to read past the end of a file)
eofbitThe stream has reached the end of a file
failbitA non-fatal error occurred (e.g. the user entered letters when the program was expecting an integer)
https://www.learncpp.com/cpp-tutorial/stream-states-and-input-validation/
Member functionMeaning
good()Returns true if the goodbit is set (the stream is ok)
bad()Returns true if the badbit is set (a fatal error occurred)
eof()Returns true if the eofbit is set (the stream is at the end of a file)
fail()Returns true if the failbit is set (a non-fatal error occurred)
clear()Clears all flags and restores the stream to the goodbit state
clear(state)Clears all flags and sets the state flag passed in
rdstate()Returns the currently set flags
setstate(state)Sets the state flag passed in

Stream Manipulators and Formatting

Defined in header <ios>
boolalpha
noboolalpha
switches between textual and numeric representation of booleans
(function)
showbase
noshowbase
controls whether prefix is used to indicate numeric base
(function)
showpoint
noshowpoint
controls whether decimal point is always included in floating-point representation
(function)
showpos
noshowpos
controls whether the + sign used with non-negative numbers
(function)
skipws
noskipws
controls whether leading whitespace is skipped on input
(function)
uppercase
nouppercase
controls whether uppercase characters are used with some output formats
(function)
unitbuf
nounitbuf
controls whether output is flushed after each operation
(function)
internal
left
right
sets the placement of fill characters
(function)
dec
hex
oct
changes the base used for integer I/O
(function)
fixed
scientific
hexfloat
defaultfloat(C++11)
changes formatting used for floating-point I/O
(function)
 
Defined in header <istream>
wsconsumes whitespace
(function template)
 
Defined in header <ostream>
endsoutputs ‘\0
(function template)
flushflushes the output stream
(function template)
endloutputs ‘\n‘ and flushes the output stream
(function template)
emit_on_flush
noemit_on_flush(C++20)
controls whether a stream’s basic_syncbuf emits on flush
(function template)
flush_emit(C++20)flushes a stream and emits the content if it is using a basic_syncbuf
(function template)
 
Defined in header <iomanip>
resetiosflagsclears the specified ios_base flags
(function)
setiosflagssets the specified ios_base flags
(function)
setbasechanges the base used for integer I/O
(function)
setfillchanges the fill character
(function template)
setprecisionchanges floating-point precision
(function)
setwchanges the width of the next input/output field
(function)
get_money(C++11)parses a monetary value
(function template)
put_money(C++11)formats and outputs a monetary value
(function template)
get_time(C++11)parses a date/time value of specified format
(function template)
put_time(C++11)formats and outputs a date/time value according to the specified format
(function template)
quoted(C++14)inserts and extracts quoted strings with embedded spaces
(function template)
https://en.cppreference.com/w/cpp/io/manip

Stringstreams

	stringstream ss; 

	ss << "Merhaba ";
	ss << "Dunya";

	string a, b, c;
	ss >> a; // Merhaba
	ss >> b; // Dunya 
	ss >> c; // 

	cout << a << endl << b << endl << c << endl<< "---";

Resource Management

  1. Kaynaklar, private yapılır.
  2. Kaynaklara erişim public metodlar yardımıyla gerçekleşir.
  3. Constructor’da kaynaklar allocate edilir
  4. Destructor’da deallocate edilir.

Böyle kaynakların yönetim sorumluluğu sınıfta olur. Nesne scope’dan çıktığında nesneye bağlı tüm kaynaklar bellekten kaldırılır.

Random Access to Streams

C++ offers two pointers while navigating the file: the get pointer and the put pointer. The first one is used for read operations, the second one for write operations.

  • seekg() is used to move the get pointer to a desired location with respect to a reference point.
  • tellg() is used to know where the get pointer is in a file.
  • seekp() is used to move the put pointer to a desired location with respect to a reference point.
  • tellp() is used to know where the put pointer is in a file.

https://stackoverflow.com/questions/53608590/what-does-the-g-stand-for-in-gcount-tellg-and-seekg

Stream Iterators

Binary Files

data alignment

pragma pack


Comments

Leave a Reply

Your email address will not be published. Required fields are marked *