directory

  • 1. Introduction of input and output classes
    • 1.C/C++ file operation comparison
    • 2. What is flow?
    • C++ I/O stream class hierarchy
    • 4. Buffered INPUT and output
    • 5. GCC compiler cinc.in_Avail ()
  • 2. Write data to the file
    • 1. Document writing exercises
    • 2. How to output information to the file and screen at the same time?
  • 3. Read data from files
    • 1. Check whether the file is opened successfully
    • 2. Check whether the file ends
    • 3. Reading files
    • 4. Can the bad() function be used to determine whether the file stream opened successfully?

1. Introduction of input and output classes

1.C/C++ file operation comparison

2. What is flow?

A stream is a sequence of data.

A stream has two endpoints, a data source on one side and a program on the other.

An I/O stream represents an input source or output destination. Streams can represent many different kinds of sources and targets, including disk files, devices, other programs, and memory arrays.

Streams support many different types of data, including simple bytes, primitive data types, localized characters, and objects. Some streams simply pass data; Others manipulate and transform data in useful ways.

No matter how they work internally, all streams provide the same simple model to programs that use them: streams are sequences of data.

The program uses the input stream to read one item of data at a time from a source:

The program uses the output stream to write data to the destination, one item at a time:



From:I/O streams

C++ I/O stream class hierarchy

There are five main types of C++ flow classes:

  1. Stream base classes (iOS_Base and ios)Copy the code
  2. Standard input/output stream class (istream/ostream/iostream)Copy the code
  3. String stream class (istringstream/ostringstream)Copy the code
  4. File stream class (ifstream/ofstream/fstream)Copy the code
  5. The buffer class (streambuf/stringbuf/filebuf)Copy the code

The standard input/output stream objects CIN and cout are instances of the classes istream and ostream, respectively

String stream: Formats various types of data into a string. You can use an I/O manipulator to control the format. Conversely, you can read various data from a string.

4. Buffered INPUT and output

C++ I/O streams have internal buffers. C = cine.get (void) reads one character at a time and leaves the newline generated by the Enter key in the input queue

#include<iostream>

using namespace std;

int main(a) {
    char c;
    int i = 0;
    do {
        c = cin.get(a); cout << ++i <<":" <<
            static_cast<int>(c) << endl;
    } while(c ! ='q');
    return 0;

}
Copy the code

2. Cin. Get () does not work because there are newline characters left in the buffer after cin

#include <iostream>

int main(a)
{
	// Get the buffer pointer to the cin object

	auto p = std::cin.rdbuf(a);// Read characters from keyboard into buffer, leaving all characters in buffer

	auto x = std::cin.peek(a); std::cout <<"x= " << x << std::endl;
	// Displays the number of characters in the buffer
	// Save the initial value because the value returned by each read is different
	auto count = p->in_avail(a); std::cout <<"There are " << count << "characters in the buffer." << std::endl;
	// Remove all the characters from the buffer and display them
	for (int i = 0; i < count; i++)
	{
		std::cout << i + 1 << ":" << std::cin.get() << std::endl;
	}

	std::cin.get(a);return 0;
}
Copy the code

5. GCC compiler cinc.in_Avail ()

When using the GCC compiler, there is an unexpected case:

No matter how many characters are entered, the cine.in_avail () function always returns 0.

This is due to a problem in the accompanying libstdc++ implementation of the GCC compiler (which can be seen as a bug, or a feature, of the standard library GCC implementation).

The solution is to insert the following line of code before using CIN

cin.sync_with_stdio(false);

GCC’s libstdc++ ensures that cin C++ is synchronized with stdin C by default.

2. Write data to the file

Ofstrem writes data to text files.

The flow of output data:



If the file already exists, delete the file directly.

Writing Data to a File — Auto Type Recognition

1. Document writing exercises

Output << “Lilei” << “” << 90.5 << endl; output <<” Lilei “<< 90.5 << endl; Output << “HanMeimei” << “” << 85 << endl; 4. Open the file with a text editor and check the result against the code statement

//std::c++latest
#include <fstream>
#include <iostream>
#include <filesystem>

using std::ifstream;
using std::ofstream;
using std::cout;
using std::endl;
namespace fs = std::filesystem;

int main(a)
{
	// The first step is to associate the file

	fs::path p{ "scores.txt" };

	// Create a stream output object
	ofstream output{ p };

	double lileiScore{ 90.5 };
	int hanmeimeiScore{ 84 };

	output << "Lilei " << lileiScore << endl;
	output << "HanMeimei " << hanmeimeiScore << endl;

	output.close(a); cout <<"size of " << p << " is " << fs::file_size(p) << endl;
	std::cin.get(a);return 0;
}
Copy the code

Methods of opening an output file stream include:

2. How to output information to the file and screen at the same time?

In the software debugging technology, a very important technology is to write some information in the software running process to the “log file”. But the information should also be displayed on the screen so that programmers can view it in real time. The simplest way is this:

std::ofstream output("debug.log", ios::out);
output << __FILE__ << ":" << __LINE__ << "\t" << "Variable x = " << x;
cout << __FILE__ << ":" << __LINE__ << "\t" << "Variable x = " << x;
Copy the code

Let’s use Streambuf to construct a class of its own to do this

#include <streambuf>
#include <iostream>
#include <fstream>

// The Linux tee command is used to read the standard input data and output its contents to a file.
// The tee instruction reads data from the standard input device, outputs its contents to the standard output device, and saves it as a file.
class teebuf : public std::streambuf
{
public:
    // Construct a streambuf which tees output to both input
    // streambufs.
    teebuf(std::streambuf* sb1, std::streambuf* sb2)
        : sb1(sb1)
        , sb2(sb2)
    {
    }
private:
    // This tee buffer has no buffer. So every character "overflows"
    // and can be put directly into the teed buffers.
    virtual int overflow(int c)
    {
        if (c == EOF)
        {
            return! EOF; }else
        {
            int const r1 = sb1->sputc(c);
            int const r2 = sb2->sputc(c);
            returnr1 == EOF || r2 == EOF ? EOF : c; }}// Sync both teed buffers.
    virtual int sync(a)
    {
        int const r1 = sb1->pubsync(a);int const r2 = sb2->pubsync(a);return r1 == 0 && r2 == 0 ? 0 : - 1;
    }
private:
    std::streambuf* sb1;
    std::streambuf* sb2;
};

class teestream : public std::ostream
{
public:
    // Construct an ostream which tees output to the supplied
    // ostreams.
    teestream(std::ostream& o1, std::ostream& o2);
private:
    teebuf tbuf;
};

teestream::teestream(std::ostream& o1, std::ostream& o2)
    : std::ostream(&tbuf)
    , tbuf(o1.rdbuf(), o2.rdbuf() {}int main(a)
{
    std::ofstream output("debug.log");
    // create file/screen output stream object tee
    teestream tee(std::cout, output);

    auto x = 1.1;
    tee << __FILE__ << ":" << __LINE__ << "\t" << "Variable x = " << x;

    return 0;
}
Copy the code

Effect:

3. Read data from files

Ifstrem reads data from a text file and detects whether the file has been opened successfully.



Understand data formats

To read data correctly, you must know exactly what format the data is stored in.

Read data from a file stream with a stream extract operator. The length of the information read is related to the type of the variable to the right of the stream extract operator.

1. Check whether the file is opened successfully

Possible error:

1. The file does not exist when the file is read. 2

Check whether the file is opened correctly:

2. Fail () returns true, the file is not open

ofstream output("scores.txt");
if (output.fail())  {
    cout << R"(Can't open file "scores.txt"!) ";
  }
Copy the code

2. Check whether the file ends

If you don’t know how many lines are in the file and you want to read them out, use eof() to check if it’s the end of the file. Since get returns an int, cast it to screen.

ifstream in("scores.txt");
while (in.eof() = =false) {
  cout << static_cast<char>(in.get());
}
Copy the code

3. Reading files

Create file input stream, open file score.txt, read data from file with >> 3, use fail() function to check whether file is open 4, put read statement into loop, use eof() as loop condition 5, close file

//std::c++latest
#include <fstream>
#include <iostream>
#include <filesystem>
#include <string>
using std::ifstream;
using std::ofstream;
using std::cout;
using std::endl;
using std::string;
namespace fs = std::filesystem;

int main(a)
{
	// The first step is to associate the file

	fs::path p{ "scores.txt" };

	// Create a stream input object
	ifstream input{ p };

	// The third step is to use fail to determine whether the stream is open properly
	if (input.fail())
	{
		cout << "Can't open file " << p << endl;
		std::cin.get(a);return 0;
	}
	// Step 4, define some variables to store the data
	string name{ "" };
	double score{ 0.0 };

	// Read the name and score from the file
	//input >> name >> score;
	//cout << name << " " << score << endl;
	//input >> name >> score;
	//cout << name << " " << score << endl;
	
	while (input.eof() = =false)
	{
		cout << static_cast<char>(input.get());
	}

	std::cin.get(a);return 0;
}
Copy the code

4. Can the bad() function be used to determine whether the file stream opened successfully?

In addition to the fail() function, there is a bad() function in the ifstream and ofstream classes.

So can we use bad() instead of fail() to determine whether the stream opened successfully?

Bad () returns true if an unexpected problem occurs, such as file corruption or hardware failure, when the data was last read.