How to Read a Struct From Pipe C++

C++ Tutorial - fstream: input and output

cplusplus_icon.png

Bookmark and Share




bogotobogo.com site search:


Stream

C++ provides methods of input and output through a mechanism known as streams.

Streams are a flexible and object-oriented approach to I/O. In this chapter, we will meet how to use streams for data output and input. We will also larn how to use the stream mechanism to read from various sources and write to diverse destinations, such as the user panel, files, and even strings.

In cout stream, we throw some variables downwards the stream, and they are written to the user's screen, or console. Streams vary in their management and their associated source or destination.

For example, the cout stream is an output stream so its direction is out. It writes data to the panel so its associated destination is console. There is another standard stream called cin that accepts input from the user. Its management is in, and its associated source is console.

cout and cin are predefined instances of streams that are defined within the std namespace in C++.

C++ uses type-safe I/O, that is, each I/O performance is executed in a manner sensitive to the information type. If an I/O member part has been defined to handle a particular data blazon, and so that member function is called to handle that data type. If there is no match betwixt the type of the bodily information and a function for treatment that information type, the compiler reports an error. Therefore, improper data cannot sneak through the organization different in C, where allowing for some subtle errors.

Users can specify how to perform I/O for objects of user-defined types by overloading the stream insertion operator (<<) and the stream extraction operator (>>). This extensi- bility is one of C++'southward most valuable features.

cin & excedption

In the code below, the variable x is an integer but a character input is assigned to it. Though the default setting for exceptions() is goodbit, the overloaded exceptions(iostate) part gives united states of america command over how we set the beliefs for the incorrect input. The line cin.exceptions(ios::failbit) causes failbit to throw exception.

#include <iostream> #include <exception>  using namespace std;  int main() { 	int 10;  	// brand failbit to throw exception          cin.exceptions(ios::failbit);          try { 		cin >> 10; 		cout << "input = " << x << endl; 	} 	take hold of(ios_base::failure &fb;) { 		cout << "Exception:" << fb.what() << endl; 		cin.articulate(); 	}  	return 0; }        

Output may exist different depending on the implementation:

a Exception:ios_base::failbit prepare        

File Writing

<fstream> library provides functions for files, and we should simply add #include <fstream> directives at the commencement of our program.

To open a file, a filestream object should first be created. This is either an ofstream object for writing, or an ifstream object for reading.

The declaration of a filesream object for writing output begins with the ofstream, so a proper name for that filestream object followed by parentheses specifying the file to write to: ofstream object_name ("file_name");

#include <fstream> #include <string> #include <iostream> using namespace std ;  int master() { 	string theNames = "Edsger Dijkstra: Made advances in algorithms, the semaphore (programming).\n" ; 	theNames.append( "Donald Knuth: Wrote The Art of Computer Programming and created TeX.\n" ) ; 	theNames.append( "Leslie Lamport: Formulated algorithms in distributed systems (e.1000. the bakery algorithm).\n") ;  	theNames.suspend( "Stephen Cook: Formalized the notion of NP-completeness.\n" ) ;          ofstream          ofs( "theNames.txt" ) ;  	if( ! ofs )	{ 		cout << "Error opening file for output" << endl ; 		render -i ; 	} 	 	ofs << theNames << endl ; 	ofs.close() ; 	return 0 ; }        

With output equally below - theNames.txt:

Edsger Dijkstra: Fabricated advances in algorithms, the semaphore (programming). Donald Knuth: Wrote The Art of Computer Programming and created TeX. Leslie Lamport: Formulated algorithms in distributed systems (due east.g. the bakery algorithm). Stephen Cook: Formalized the notion of NP-abyss.        

ios

TABLE

ios Description
ios::out Open a file to write output
ios::in Open a file to read input
ios::app Open a file to suspend at the cease
ios::trunc Truncate the existing file (default)
ios::ate Open a file without truncating, and allow data to exist written anywhere in the file.
ios::binary Treat the file every bit binary format rather than ASCII so that the data may exist stored in not-ASCII format.

When a filestream object is created, the parentheses following its name can optionally contain additional arguments. The arguments specify a range of file modes to command the behavior of the filestream object. Since these file modes are part of the ios namespace, they must be explicitly addressed using that prefix as shown the table above.

Several mides may be specified if they are separated past a pipe, "|". To open a file for binary output looks like this:

ofstream object_name ("file_name", ios::out | ios::binary);        

The default behavior when no modes are specified considers the file as a text file that will be truncated after writing. One of the most commonly used mode is ios::app, which ensures existing content will be appended when new output is written to the file.

File Reading

The ifstream object has a go() function that tin can be used to read a file. In the example beneath, nosotros read the input file i character at a time:

#include <string> #include <fstream> #include <iostream> using namespace std ;  int master() {   char alphabetic character ;   int i ;   string line ;          ifstream          reader( "Shakespeare.txt" ) ;    if( ! reader ) {     cout << "Mistake opening input file" << endl ;     render -i ;   }    for( i = 0; ! reader.eof() ; i++ ) {     reader.go( alphabetic character ) ;     cout << letter ;  	/*          getline( reader , line ) ;     cout << line << endl ; 	*/   }    reader.shut() ;      return 0 ; }        

Output is:

Macbeth: To-morrow, and to-morrow, and to-morrow, Creeps in this piffling step from day to day, To the last syllable of recorded fourth dimension; And all our yesterdays have lighted fools The way to dusty decease. Out, out, brief candle! Life's but a walking shadow, a poor player, That struts and frets his 60 minutes upon the stage, And and so is heard no more. Information technology is a tale Told by an idiot, full of sound and fury, Signifying nothing.        

Like to the to a higher place case, the following gets words from the Linux dictionary /usr/share/dict/words, and puts into a vector afterwards filtering words that start with lower case letter:

#include <iostream> #include <fstream> #include <cord> #include <vector>  using namespace std;  int master() {   string line;   vector            dictionary;            ifstream            dict_reader("/usr/share/dict/words");   if( !dict_reader ) {     cout << "Fault opening input file - dict  " << endl ;     go out(1) ;   }    while(!dict_reader.eof()) {            getline(dict_reader,line);     if(line[0] >= 'a' && line[0] <= 'z')       dictionary.push_back(line);   }   for(int i = 0; i < lexicon.size(); i++) {     cout << dictionary[i] << " " << endl;   } }                  

The output is:

a a' a- a. a1 aa aaa ... zythum zyzzyva zyzzyvas zZt        

The fstream::eof() may non work under certain conditions, so sometimes nosotros may want the following lines:

          // while(!dict_reader.eof()) {  //   getline(dict_reader,line);  =>     while(getline(dict_reader,line)) {        

The getline() can have additional argument for a delimiter where to stop reading. This tin be used to read in tabulated data:

Tommy	Tutone	San Francisco	401-867-5309 Celine	Dion	Lava Canada	450-978-9555  LA	Times	Los Engeles	800-252-9141        

Each detail in the recode higher up is separated by tab and line feed. The following code reads in the data and prints out each particular in a line.

#include <fstream> #include <iostream> #include <string> using namespace std;  int main() { 	const int RECORDS = 12; 	ifstream reader("PhoneBook.txt"); 	if(!reader) { 		cout << "Mistake: cannot open input file" << endl; 		render -one; 	} 	string detail[RECORDS]; 	int i = 0; 	while(!reader.eof()) { 		if((i+1) % 4 == 0)  			getline(reader,detail[i++],'\n'); 		else 			getline(reader,item[i++],'\t'); 	} 	i = 0; 	while(i < RECORDS) { 		cout << "Offset name " << item[i++] << endl; 		cout << "Last name " << item[i++] << endl; 		cout << "Area " << item[i++] << endl; 		cout << "Phone " << item[i++] << endl << endl; 	} 	reader.close(); 	return 0; }        

Output:

Start name Tommy Last proper noun Tutone Area San Francisco Phone 401-867-5309  Outset proper name Celine Final proper noun Dion Area Lava Canada Phone 450-978-9555  Outset name LA Last proper name Times Area Los Engeles Telephone 800-252-9141        

Reading in information to fill a vector - A

The following example reads in int information from a file, and and so fills in vector. If the infinite is not enough to hold the data, the vector resizing it by ten.

#include <iostream> #include          <fstream>          #include <vector>  using namespace std;  int master() {   // vector with 10 elements   std::vector<int>five(10);    // ifp: input file pointer   std::ifstream ifp("data", ios::in);    int i = 0;   while(!ifp.eof())   {     ifp >> v[i++];     if(i % 9 == 0) v.resize(5.size() + x);   }    std::vector<int>::iterator information technology;   for(it = v.begin(); information technology != v.stop(); ++it )    std:: cout << *it << ' ';   std::cout << endl; }        

The input file looks like this:

i ii three 4 v 6 7 8 9 10 eleven 12 13 14 15 16 17 18 nineteen 20 21 22 22 24 25        

Output:

1 two 3 4 v half dozen vii 8 9 10 eleven 12 xiii fourteen 15 16 17 18 19 20 21 22 22 24 25 0 0 0 0 0        

Reading in data to fill a vector - B

The post-obit instance is almost the aforementioned as the previous example: information technology reads in string data from a file and fills in vector.

The std::istreamstd::ctype_base::space is the default delimiter which makes it end reading further graphic symbol from the source when it sees whitespace or newline.

As we can see from the data file (names) we're using:

Mao Asada Carolina Kostner Ashley Wagner Gracie Gold Akiko Suzuki Kanako Murakami Adelina Sotnikova Kaetlyn Osmond Yuna Kim Julia Lipnitskaia        

equally an input. When we reads in the information, it stores first_name and last name into the vector. But we want to treat them as a pair. So, nosotros later put the pair into a map.

Here is the lawmaking:

/* w.cpp */ #include <iostream> #include <fstream> #include <string> #include <vector> #include <map>  using namespace std;  int read_words(vector<string>& words, ifstream& in) {   int i = 0;   while(!in.eof())     in >> words[i++];   render i-i; }  int master() {   ifstream ifp("names");    vector<string> westward(500);   int number_of_words = read_words(w, ifp);   w.resize(number_of_words);    for(motorcar information technology : w)     cout << it << " ";   cout << endl;    map<cord, string> wMap;    for(int i = 0; i  <  number_of_words;) {     wMap.insert(pair<string, string>(w[i], w[i+1]));     i += 2;   }    cout << "wMap.size()=" << wMap.size() << endl;   for(auto information technology = wMap.brainstorm(); it != wMap.cease(); it++)     cout <<  information technology->first << " " << it->second << endl; }        

Output:

wMap.size()=10 Adelina Sotnikova Akiko Suzuki Ashley Wagner Carolina Kostner Gracie Gold Julia Lipnitskaia Kaetlyn Osmond Kanako Murakami Mao Asada Yuna Kim        

Annotation that nosotros're using C++eleven motorcar keyword that can deduce the type from context, we should let the compiler know we want the file compiled with C++11:

thou++          -std=c++xi          -o w w.cpp        

Alignment and field width - Russian Peasant Multiplication

Here is an example that shows output of 3 integers with field width v and left aligned.

// Russian Peasant Multiplication   #include <iostream> #include <iomanip> using namespace std;  int RussianPeasant(int a, int b) { 	int x = a,  y = b; 	int val = 0; 	cout << left << setw(v) << x << left << setw(5) << y << left << setw(five) << val << endl; 	while (x > 0) { 		if (ten % 2 == i) val = val + y; 		y = y << 1;  // double 		x = x >> one;  // half 		cout << left << setw(5) << x << left << setw(5) << y << left << setw(5) << val << endl;  	} 	return val; }  int master() { 	RussianPeasant(238, 13); 	return 0; }        

The output should expect like this:

238  13   0          119          26          0          59          52          26          29          104          78 14   208  182          7          416          182          three          832          598          1          1664          1430 0    3328          3094        

Actually, the multiplication is known equally Russian Peasant Multiplication. Whenever x is odd, the value of y is added to val until x equals to zero, and then information technology returns 3094 .

Retasting C file IO - fseek

What would be the output from the code below.

#include<stdio.h>  int principal() {     FILE *fp;     char c[1024];     fp = fopen("test.txt", "r");  // "Kernighan and Ritchie"      c[0] = getc(fp);              // c[0] = M     fseek(fp, 0, SEEK_END);       // file position moved to the cease     fseek(fp, -7L, SEEK_CUR);     // 7th from the end, with is 'R' of "Ritchie"     fgets(c, 6, fp);              // read 6-ane characters from 'R'     puts(c);                      // "Ritch"     render 0; }        

Retasting C file IO - fgets

Q: In a file contains the line "The C Programming Language\r\north".
This reads this line into the array s using fgets().
What volition s contain?

Ans: "The C Programming Language\r\0"

That'south because char *fgets(char *south, int due north, FILE *stream) reads characters from stream into the cord s.
It stops when information technology reads either n - 1 characters or a newline character, whichever comes start.
Therefore, the string str contains "The C Programming Linguistic communication\r\0".

Retasting C file IO - scanf

scanf() returns the number of items of the argument list successfully filled. In the lawmaking below, though 99 is given, the out is 1 because scanf() returns the number of input which is 1.

#include <stdio.h>  int master() {     int i;     /* 99 is given for the input */     printf("%d\n", scanf("%d", &i;));  /* Though i = 99, print output is i */     return 0; }        

argc/argv

int main(int argc, char *argv[]){}        
  1. argc volition have been set to the count of the number of strings that
  2. argv will point to, and argv volition accept been set to point to an assortment of pointers to the individual strings
  3. argv[0] will point to the program name string, what ever that is,
  4. argv[1] will point to the first statement cord,
  5. argv[2] will point to the second argument cord, and then on, with
  6. argv[argc-1] pointing to the concluding argument string, and
  7. argv[argc] pointing at a Nada pointer

wilsonfeak1952.blogspot.com

Source: https://www.bogotobogo.com/cplusplus/fstream_input_output.php

0 Response to "How to Read a Struct From Pipe C++"

Post a Comment

Iklan Atas Artikel

Iklan Tengah Artikel 1

Iklan Tengah Artikel 2

Iklan Bawah Artikel