C++017-C++ file reading and writing application

C++017-C++ file reading and writing application

insert image description here

Online practice:
http://noi.openjudge.cn/
https://www.luogu.com.cn/

C++ file reading and writing application

Reference:
Chinese coding miscellaneous talk
https://space.bilibili.com/627875426
Detailed explanation of C++ file reading and writing (ofstream, ifstream, fstream)

insert image description here

CSP-J target

· 【2】The basic concept of the file, the basic operation of the text file
· 【2】Text file type and binary file type
· 【2】File redirection, file read and write and other operations

1. Basic concepts of files and basic operations of text files

In C++, a file is a data storage method, which can be a text file or a binary file. A text file is a file that stores data in a text format, and each character is stored as a text file with its ASCII code value, which can be opened and edited with a common text editor. In C++, you can use the file streams in the standard library to open, read, write, and close files.

Open a file: Use a file stream object (eg ifstream or ofstream) to create a file object and open the file. When opening a file, you can specify the opening mode, such as read-only, write-only, append, etc.
Reading a file: Use an input stream object (such as ifstream) to read data from a file. Different read functions can be used, such as getline, get, read, etc. To read a file, the file must first be opened.
Write to file: Use an output stream object (eg ofstream) to write data to a file. Different writing functions can be used, such as put, write, << operator, etc. To write to a file, the file must first be opened.
Close the file: Use the close() function of the file stream object to close the file. After a file is closed, it can no longer be read from or written to.
insert image description here

#include <fstream>  
ofstream         //文件写操作 内存写入存储设备 (由ostream引申而来)   
ifstream         //文件读操作,存储设备读区到内存中  (由ostream引申而来) 
fstream          //读写操作,对打开的文件可进行读写操作  (由iostream引申而来) 

2. Text file type and binary file type

Reference: https://www.cnblogs.com/xkfz007/archive/2011/07/21/2176994.html
insert image description hereinsert image description here

insert image description here

text file type

txt is a plain text format, which is simply an ordinary text file without format; csv is a comma-separated value file, which separates data fields with commas; json is a lightweight data exchange format that stores data in the form of key-value pairs ;Xml is an extensible markup language, used to store and transmit data; html is a hypertext markup language, a file format used to create web pages and other visual browser interfaces.

binary file type

There are many types of binary files, and the common ones are as follows:
Executable files: generally files with the suffix .exe, which can be run directly.
Dynamic link library (DLL): generally a file with the suffix .dll, which is a dynamic link library file that contains some functions and data called by the program.
Static link library (LIB): generally a file with the suffix .lib, which is also a library file, but unlike a DLL file, it is linked into the program at compile time.
Data file: generally a file with a suffix of .dat, .bin, etc., which stores the data required by the program.
Image file: generally a file with a suffix of .bmp, .jpg, .png, etc., storing the binary data of the image.
Audio file: generally a file with a suffix of .mp3, .wav, etc., storing audio binary data.
For example, an .exe file is a binary file that can be directly executed, such as a game client in a game. A DLL file is a dynamic link library, such as some system DLL files in the Windows system. A LIB file is a statically linked library file, such as some common libraries used in development. And image files, audio files, etc., they are all binary data storage methods.

Binary Viewer

A file with the following content:

ABCD
abcd

Open with Binary Viewer
insert image description here

Hexadecimal is the byte stream content, and the right side is the character stream content. The content format in Hexadecimal is a hexadecimal number, because the character stored in the operating system is an ASCII code value, so the value in the red box on the left is the ASCII code value in hexadecimal form, and the right side is the ASCII code value The character content corresponding to the ASCII code value. . For example, the first hexadecimal number on the left is 41, and its corresponding decimal is 4*16 + 1=65. In the ASCII code table, 65 corresponds to A, as shown by the first letter in the box on the right side of the above figure. Show. The ASCII code table is given below.
insert image description here

3. File redirection, file read and write and other operations

close file

When the file read and write operations are complete, we must close the file to make the file accessible again. The member function close() is responsible for discharging the data in the cache and closing the file. Once this function is called, the original stream object can be used to open other files, and this file can be accessed by other processes again. In order to prevent the open file from being connected to the stream object when it is destroyed, the destructor will automatically call the closing function close.

File Operations - Writing to Text Files

Text files typically organize data in lines.
In the fstream class, the member function open() implements the operation of opening the file, thereby associating the data stream with the file, and performing read and write operations on the file through the ofstream, ifstream, and fstream objects

Function: open()

 
public member function
 
void open ( const char * filename,
            ios_base::openmode mode = ios_base::in | ios_base::out );
 
void open(const wchar_t *_Filename,
        ios_base::openmode mode= ios_base::in | ios_base::out,
        int prot = ios_base::_Openprot)
 

The way to open the file is defined in the ios class (so the base class of streaming I/O), there are several ways:
insert image description here

包含头文件:#include <fstream>
类:ofstream(output file stream)

The mode (method) of ofstream to open the file:
For ofstream, no matter which mode is used to open the file, if the file does not exist, the file will be created.
ios::out Default value: the file content will be truncated.
ios::trunc truncates the file contents. (truncate)
ios::app does not truncate the file content, but only appends the file at the end of the file. (append)

Example:

#include <iostream>
#include <fstream>  // ofstream类需要包含的头文件。
using  namespace std;

int main()
{
    
    
	// 文件名一般用全路径,书写的方法如下:
	//  1)"D:\data\txt\test.txt"       // 错误。
	//  2)R"(D:\data\txt\test.txt)"   // 原始字面量,C++11标准。
	//  3)"D:\\data\\txt\\test.txt"   // 转义字符。
	//  4)"D:/tata/txt/test.txt"        // 把斜线反着写。
	//  5)"/data/txt/test.txt"          //  Linux系统采用的方法。
	string filename = R"(D:\data\txt\test.txt)";
	//char    filename[] = R"(D:\data\txt\test.txt)";

	// 创建文件输出流对象,打开文件,如果文件不存在,则创建它。
	// ios::out     		缺省值:会截断文件内容。
	// ios::trunc  		截断文件内容。(truncate)
	// ios::app   			不截断文件内容,只在文件未尾追加文件。(append)
	//ofstream fout(filename);
	//ofstream fout(filename, ios::out);
	//ofstream fout(filename, ios::trunc);
	//ofstream fout(filename, ios::app);
	
	ofstream fout;
	fout.open(filename,ios::app);

	// 判断打开文件是否成功。
	// 失败的原因主要有:1)目录不存在;2)磁盘空间已满;3)没有权限,Linux平台下很常见。
	if (fout.is_open() == false)
	{
    
    
		cout << "打开文件" << filename << "失败。\n";  return 0;
	}

	// 向文件中写入数据。
	fout << "你好 淄博1\n";
	fout << "你好 淄博2\n";
	fout << "你好 淄博3\n";

	fout.close();	   // 关闭文件,fout对象失效前会自动调用close()。

	cout << "操作文件完成。\n";
}

File operations - read text files

包含头文件:#include <fstream>
类:ifstream

The mode (method) of ifstream to open the file:
For ifstream, if the file does not exist, it will fail to open the file.
ios::in default.

Example:

#include <iostream>
#include <fstream>  // ifstream类需要包含的头文件。
#include <string>     // getline()函数需要包含的头文件。
using  namespace std;

int main()
{
    
    
	// 文件名一般用全路径,书写的方法如下:
	//  1)"D:\data\txt\test.txt"       // 错误。
	//  2)R"(D:\data\txt\test.txt)"   // 原始字面量,C++11标准。
	//  3)"D:\\data\\txt\\test.txt"   // 转义字符。
	//  4)"D:/tata/txt/test.txt"        // 把斜线反着写。
	//  5)"/data/txt/test.txt"          //  Linux系统采用的方法。
	string filename = R"(D:\data\txt\test.txt)";
	//char    filename[] = R"(D:\data\txt\test.txt)";

	// 创建文件输入流对象,打开文件,如果文件不存在,则打开文件失败。。
	// ios::in     			缺省值。
	//ifstream fin(filename);
	//ifstream fin(filename, ios::in);
	
	ifstream fin;
	fin.open(filename,ios::in);

	// 判断打开文件是否成功。
	// 失败的原因主要有:1)目录不存在;2)文件不存在;3)没有权限,Linux平台下很常见。
	if (fin.is_open() == false)
	{
    
    
		cout << "打开文件" << filename << "失败。\n";  return 0;
	}

	 第一种方法。
	//string buffer;  // 用于存放从文件中读取的内容。
	 文本文件一般以行的方式组织数据。
	//while (getline(fin, buffer))
	//{
    
    
	//	cout << buffer << endl;
	//}

	 第二种方法。
	//char buffer[16];   // 存放从文件中读取的内容。
	 注意:如果采用ifstream.getline(),一定要保证缓冲区足够大。
	//while (fin.getline(buffer, 15))
	//{
    
    
	//	cout << buffer << endl;
	//}

	// 第三种方法。
	string buffer;
	// 析取器(>>),>>遇到空格、换行符后停止读取文件,待再次调用时才接着读取。可以理解为>>不读空格、换行符
	while (fin >> buffer)
	{
    
    
		cout << buffer << endl;
	}

	fin.close();	   // 关闭文件,fin对象失效前会自动调用close()。

	cout << "操作文件完成。\n";
}

insert image description here

File Operations - Writing Binary Files

The binary file organizes data in the form of data blocks, and writes the data in memory directly to the file.

包含头文件:#include <fstream>
类:ofstream(output file stream)

The mode (method) of ofstream to open the file:
For ofstream, no matter which mode is used to open the file, if the file does not exist, the file will be created.

ios::out Default value: the file content will be truncated.
ios::trunc truncates the file contents. (truncate)
ios::app does not truncate the file content, but only appends the file at the end of the file. (append)
ios::binary Open the file in binary mode.

Some details on manipulating text and binary files:

1) Under the Windows platform, the newline symbol of the text file is "\r\n".
2) Under the linux platform, the newline symbol of the text file is "\n".
3) On the Windows platform, if you open a file in text mode, when writing data, the system will convert "\n" into "\r\n"; when reading data, the system will convert "\r\n " into "\n". If the file is opened in binary mode, neither writing nor reading will be converted.
4) Under the Linux platform, open the file in text or binary mode, the system will not do any conversion.
5) When reading a file in text mode, it will stop when encountering a newline character, and there is no newline character in the read content; when reading a file in binary mode, it will not stop when encountering a newline character, and the read content will Contains newlines (newlines are treated as data).
6) In actual development, from the perspective of compatibility and semantics, generally: a) Open a text file in text mode and operate it with the method of line; b) Open a binary file in binary mode and operate it with the method of data block; c) Open text files and binary files in binary mode, and manipulate them with data blocks, which means that you don't care about the content of the data. (such as copying files and transferring files) d) Do not open binary files in text mode, and do not use line methods to manipulate binary files, it may destroy the format of binary data files, and it is not necessary. (Because the value of a certain byte in the binary file may be a newline character, but its meaning is not a newline, it may be a certain byte in the integer n bytes)

Example:

#include <iostream>
#include <fstream>  // ofstream类需要包含的头文件。
using  namespace std;

int main()
{
    
    
	// 文件名一般用全路径,书写的方法如下:
	//  1)"D:\data\bin\test.dat"       // 错误。
	//  2)R"(D:\data\bin\test.dat)"   // 原始字面量,C++11标准。
	//  3)"D:\\data\\bin\\test.dat"   // 转义字符。
	//  4)"D:/tata/bin/test.dat"        // 把斜线反着写。
	//  5)"/data/bin/test.dat"          //  Linux系统采用的方法。
	string filename = R"(.\test.dat)";
	//char    filename[] = R"(D:\data\bin\test.dat)";

	// 创建文件输出流对象,打开文件,如果文件不存在,则创建它。
	// ios::out     		缺省值:会截断文件内容。
	// ios::trunc  		截断文件内容。(truncate)
	// ios::app   			不截断文件内容,只在文件未尾追加文件。(append)
	// ios::binary   		以二进制方式打开文件。
	//ofstream fout(filename, ios::binary);
	//ofstream fout(filename, ios::out | ios::binary);
	//ofstream fout(filename, ios::trunc | ios::binary);
	//ofstream fout(filename, ios::app | ios::binary);

	ofstream fout;
	fout.open(filename, ios::app | ios::binary);

	// 判断打开文件是否成功。
	// 失败的原因主要有:1)目录不存在;2)磁盘空间已满;3)没有权限,Linux平台下很常见。
	if (fout.is_open() == false)
	{
    
    
		cout << "打开文件" << filename << "失败。\n";  return 0;
	}

	// 向文件中写入数据。
	struct st_girl {
    
                   // 超女结构体。
		char name[31];         // 姓名。
		int    no;                    // 编号。
		char memo[301];      // 备注。
		double weight;         // 体重。
	};
	struct st_girl girl = {
    
     "西施",3,"中国历史第一美女。" ,45.8 };
	fout.write((const char *)& girl, sizeof(st_girl));   // 写入第一块数据。
	struct st_girl girl2 = {
    
     "冰冰",8,"也是个大美女哦。",55.2};
	fout.write((const char*)&girl2, sizeof(st_girl));     // 写入第二块数据。

	fout.close();	   // 关闭文件,fout对象失效前会自动调用close()。

	cout << "操作文件完成。\n";
}

File Operations - Reading Binary Files

包含头文件:#include <fstream>
类:ifstream

The mode (method) of ifstream to open the file:
For ifstream, if the file does not exist, it will fail to open the file.
ios::in default.
ios::binary opens the file in binary mode.

Example:

#include <iostream>
#include <fstream>  // ifstream类需要包含的头文件。
using  namespace std;

int main()
{
    
    
	// 文件名一般用全路径,书写的方法如下:
	//  1)"D:\data\bin\test.dat"       // 错误。
	//  2)R"(D:\data\bin\test.dat)"   // 原始字面量,C++11标准。
	//  3)"D:\\data\\bin\\test.dat"   // 转义字符。
	//  4)"D:/tata/bin/test.dat"        // 把斜线反着写。
	//  5)"/data/bin/test.dat"          //  Linux系统采用的方法。
	string filename = R"(.\test.dat)";
	//char    filename[] = R"(D:\data\bin\test.dat)";

	// 创建文件输入流对象,打开文件,如果文件不存在,则打开文件失败。。
	// ios::in     			缺省值。
	// ios::binary   		以二进制方式打开文件。
	//ifstream fin(filename , ios::binary);
	//ifstream fin(filename , ios::in | ios::binary);

	ifstream fin;
	fin.open(filename, ios::in | ios::binary);

	// 判断打开文件是否成功。
	// 失败的原因主要有:1)目录不存在;2)文件不存在;3)没有权限,Linux平台下很常见。
	if (fin.is_open() == false)
	{
    
    
		cout << "打开文件" << filename << "失败。\n";  return 0;
	}

	// 二进制文件以数据块(数据类型)的形式组织数据。
	struct st_girl {
    
                   // 超女结构体。
		char name[31];         // 姓名。
		int    no;                    // 编号。   
		char memo[301];      // 备注。
		double weight;         // 体重。
	}girl;
	while (fin.read((char*)&girl, sizeof(girl)))
	{
    
    
		cout << "name=" << girl.name << ",no=" << girl.no << 
			",memo=" << girl.memo << ",weight=" << girl.weight << endl;
	}

	fin.close();	   // 关闭文件,fin对象失效前会自动调用close()。

	cout << "操作文件完成。\n";
}

insert image description here

File Operations - Random Access

1. The fstream class
The fstream class can both read text/binary files and write text/binary files.
The default mode of the fstream class is ios::in | ios::out. If the file does not exist, the file will be created; however, the original content of the file will not be cleared.
The common practice is:
1) If you only want to write data, use ofstream; if you only want to read data, use ifstream; if you want to write and read data, use fstream, which is rare. Different classes embody different semantics.
2) Under the Linux platform, the writing and reading of files have strict permission control. (The fewer permissions required, the better)
2. File location pointer
When performing read/write operations on files, the file location pointer points to the current file read/write location.
Many materials use "the position of the file read pointer" and "the position of the file write pointer", which is easy to mislead people. No matter which class is used to operate the file, there is only one file location pointer.
1) To get the file location pointer,
the member function of the ofstream class is tellp(); the member function of the ifstream class is tellg(); the fstream class has both, and the effect is the same.

std::streampos tellp();
std::streampos tellg();

2)
The function of moving the file position pointer ofstream class is seekp(); the function of ifstream class is seekg(); fstream class has both, and the effect is the same.
method one:

std::istream & seekg(std::streampos _Pos);  
fin.seekg(128);   // 把文件指针移到第128字节。
fin.seekp(128);   // 把文件指针移到第128字节。
fin.seekg(ios::beg) // 把文件指针移动文件的开始。
fin.seekp(ios::end) // 把文件指针移动文件的结尾。

Method Two:

std::istream & seekg(std::streamoff _Off,std::ios::seekdir _Way);

The enumeration type defined in ios:
enum seek_dir {beg, cur, end}; // beg- the starting position of the file; cur- the current position of the file; end- the end position of the file.

fin.seekg(30, ios::beg);    // 从文件开始的位置往后移30字节。
fin.seekg(-5, ios::cur);     // 从当前位置往前移5字节。
fin.seekg( 8, ios::cur);     // 从当前位置往后移8字节。
fin.seekg(-10, ios::end);   // 从文件结尾的位置往前移10字节。

3. Random access
Random access refers to directly moving the position pointer of the file, and reading/writing data at the specified position.

Example:

#include <iostream>
#include <fstream>  // fstream类需要包含的头文件。
using  namespace std;

int main()
{
    
    
	string filename = R"(D:\data\txt\test.txt)";
	
	fstream fs;
	fs.open(filename, ios::in | ios::out);

	if (fs.is_open() == false)
	{
    
    
		cout << "打开文件" << filename << "失败。\n";  return 0;
	}
	
	fs.seekg(26);    // 把文件位置指针移动到第26字节处。

	fs << "我是一只傻傻的小菜鸟。\n"; 

	/*string buffer; 
	while (fs >> buffer)
	{
		cout << buffer << endl;
	}*/

	fs.close();	   // 关闭文件,fs对象失效前会自动调用close()。

	cout << "操作文件完成。\n";
}

insert image description here

File operation - the mode (method) of opening the file

1. Write the file
If the file does not exist, all modes will create the file.

ios::out     		1)会截断文件;2)可以用seekp()移动文件指针。
ios:trunc  		1)会截断文件;2)可以用seekp()移动文件指针。
ios::app   		1)不会截断文件;2)文件指针始终在文件未尾,不能用seekp()移动文件指针。
ios::ate    		打开文件时文件指针指向文件末尾,但是,可以在文件中的任何地方写数据。
ios::in        		打开文件进行读操作,即读取文件中的数据。
ios::binary       	打开文件为二进制文件,否则为文本文件。

Note: ate is the abbreviation of at end, trunc is the abbreviation of truncate (truncation), and app is the abbreviation of append (append).

File operation - buffer and stream status

1. File buffer
file buffer (cache) is the memory space reserved by the system for storing input or output data.
According to the output and input stream, it is divided into output buffer and input buffer.
Note that in C++, every time a file is opened, the system will allocate a buffer for it. Different streams, buffers are independent.
Programmers don't need to care about the input buffer, only the output buffer.
In the default mode, the data is written to the disk only when the data in the output buffer is full, but this mode may not meet the needs of the business.
The operation of the output buffer:
1) The flush() member function
flushes the buffer and writes the content in the buffer to the disk file.
2) endl
wraps, then flushes the buffer.
3) unitbuf
fout << unitbuf;
set the fout output stream, and automatically refresh the buffer after each operation.
4) nounitbuf
fout << nounitbuf;
set fout output stream, let fout return to the default buffer mode.
2. Flow
state There are three flow states: eofbit, badbit and failbit, value: 1-set; or 0-clear.
When the three streams are all 0, it means everything goes well, and the good() member function returns true.
1) eofbit
When the input stream operation reaches the end of the file, eofbit will be set.
The eof() member function checks whether the stream has the eofbit set.
2) badbit
The badbit is set when an undiagnosed failure corrupts the stream. (eg: write to input stream; no space left on disk).
The bad() member function checks whether the stream has the badbit set.
3) failbit
When the input stream operation fails to read the expected character, the failbit will be set (non-fatal error, reversible, generally a software error, for example: want to read an integer, but the content is a string; the file arrives Tail) I/O failure may also set failbit.
The fail() member function checks whether the stream has the failbit set.
4) The clear() member function cleans up the stream state.
5) The setstate() member function resets the stream state.
Example 1:

#include <iostream>
#include <fstream>          // ofstream类需要包含的头文件。
#include<windows.h> //window下的Sleep
//#include <unistd.h> // linux下的 usleep(100000)
using  namespace std;

int main()
{
    
    
  ofstream fout("./bbb.txt");   // 打开文件。
  fout << unitbuf;

  for (int ii = 0; ii < 100; ii++)  // 循环1000次。
  {
    
    
    fout << "ii=" << ii << ",我是一只傻傻傻傻傻傻傻傻傻傻傻傻傻傻的鸟。\n";
    //fout.flush();      // 刷新缓冲区。
    //usleep(100000);    // 睡眠十分之一秒 linux下。
    Sleep(1);
  }

  fout.close();  // 关闭文件。
}

insert image description here

Example 2:

#include <iostream>
#include <fstream>  // ifstream类需要包含的头文件。
#include <string>     // getline()函数需要包含的头文件。
using  namespace std;

int main()
{
    
    
	ifstream fin(R"(D:\data\txt\test.txt)", ios::in);

	if (fin.is_open() == false) {
    
    
		cout << "打开文件" << R"(D:\data\txt\test.txt)" << "失败。\n";  return 0;
	}

	string buffer;
	/*while (fin >> buffer) {
		cout << buffer << endl;
	}*/
	while (true) {
    
    
		fin >> buffer;
		cout << "eof()=" << fin.eof() << ",good() = " << fin.good() << ", bad() = " << fin.bad() << ", fail() = " << fin.fail() << endl;
		if (fin.eof() == true) break;
		
		cout << buffer << endl;
	}

	fin.close();	   // 关闭文件,fin对象失效前会自动调用close()。
}

insert image description here

C++ file redirection

<1>, a simple understanding of redirection:

that is:

Change the original cin from keyboard input to file input.
Change the original cout output to the screen to output to the file.
For example: cin>>line; It turns out to be entered from the keyboard. Now it automatically reads from a certain file, and the statement is still cin>>line; unchanged.
cout << line << endl; originally output to the screen, now it is automatically written to a file, the statement is still cout << line << endl; unchanged
=======

C++ implementation method:

The rdbuf() function is defined in the <ios> header file, which is specially used to realize the redirection of C++ input and output streams.

It is worth mentioning that ios is the base class of istream and ostream classes, and the rdbuf() function is also inherited, so cin and cout can directly call this function to realize redirection. There are two syntax formats of the rdbuf() function, which
are :

streambuf * rdbuf() const;
streambuf * rdbuf(streambuf * sb);

streambuf is a class used to represent a buffer in the C++ standard library, and the pointer object of this class is used to refer to a specific stream buffer.
Among them, the first syntax format is only to return a pointer to the current stream buffer; the second syntax format is used to set the buffer pointed to by sb as the new buffer of the current stream, and return an object pointing to the old buffer .

Case 1:

#include <iostream>
#include <fstream>
using namespace std;
int main()
{
    
    
    //打开 in.txt 文件,等待读取
    ifstream fin("test.txt");
    //打开 out.txt 文件,等待写入
    ofstream fout("out.txt");
    streambuf *oldcin;
    streambuf *oldcout;
    char a[100];
    //用 rdbuf() 重新定向,返回旧输入流缓冲区指针
    oldcin = cin.rdbuf(fin.rdbuf());

    //用 rdbuf() 重新定向,返回旧输出流缓冲区指针
    oldcout = cout.rdbuf(fout.rdbuf());

    //从input.txt文件读入
    while (cin >> a){
    
    
        //写入 out.txt
        cout << a << endl;
    }


    //还原标准输入输出流
    cin.rdbuf(oldcin); // 恢复键盘输入
    cout.rdbuf(oldcout); //恢复屏幕输出
    //打开的文件,最终需要手动关闭
    fin.close();
    fout.close();
    return 0;

Case 2:

#include <iostream>
#include <ostream>
#include <fstream>
using namespace std;
main()
{
    
    
ifstream fin("./test.txt"); // 已有输入文件
ofstream fout("./output.txt"); //输出文件
streambuf *cinbackup;
streambuf *coutbackup;
coutbackup= cout.rdbuf(fout.rdbuf()); //用 rdbuf() 重新定向
cinbackup= cin.rdbuf(fin.rdbuf()); //用 rdbuf() 重新定向
cout<<"Hello world"<<endl; //去文件也
char line[100];
while (cin>>line){
    
     //从input.txt文件读入
    cout<<line<<endl; //写入 output.txt
};

// restore standard streambuf
cin.rdbuf(cinbackup); // 取消,恢复键盘输入
cout.rdbuf(coutbackup); //取消,恢复屏幕输出
return 0;
}

insert image description here

C++ implements redirection based on the console

C++ realizes redirection through the console
. The above two methods realize the redirection of input and output streams from the code level. In addition, we can also redirect input and output through the console.

#include <iostream>
#include <string>
using namespace std;
int main()
{
    
    
    string name, url;
    cin >> name >> url;
    cout << name << '\n' << url;
    return 0;
}


After compiling and running, D:\cplusproject\day0305\bin\Debug\day0305.exe is generated in the debug directory

Create a.txt in D:\cplusproject\day0305\bin\Debug

hello ah
ah ada fd
dfdf
12

run:

day0305.exe <a.txt >b.txt

Generate b.txt

Hello,
ah Ada fd

C language freopen() function realizes redirection

freopen() is defined in the <stdio.h> header file and is a function in the C language standard library, which is specially used to redirect input streams (including scanf(), gets(), etc.) and output streams (including printf(), puts(), etc.). It is worth mentioning that this function can also redirect cin and cout in C++.

#include <iostream>    //cin、cout
#include <string>      //string
#include <stdio.h>     //freopen
using namespace std;
int main()
{
    
    
    string name, url;
    //将标准输入流重定向到 in.txt 文件
    freopen("test.txt", "r", stdin);
    cin >> name >> url;

    //将标准输出重定向到 out.txt文件
    freopen("out.txt", "w", stdout);
    cout << name << "\n" << url;
    return 0;
}

insert image description here

2. File read and write operations

basic case

#include <iostream>
#include <fstream>

using namespace std;

int main() {
    
    
    // 打开文件
    ofstream outfile("data.txt");
    if (!outfile.is_open()) {
    
    
        cout << "无法打开文件" << endl;
        return 1;
    }

    // 写入数据
    outfile << "Hello, world!" << endl;
    outfile << "Hello, world222" << endl;

    // 关闭文件
    outfile.close();

    // 重新打开文件
    ifstream infile("data.txt");
    if (!infile.is_open()) {
    
    
        cout << "无法打开文件" << endl;
        return 1;
    }

    // 读取数据
    string line;
//    getline(infile, line);
//    cout << line << endl;

    while (getline(infile,line))
    {
    
    
        cout<<line<<endl;
    }

    // 关闭文件
    infile.close();

    return 0;
}

insert image description here

seekg() and tellg() functions to read data from a file

Determine whether the file is opened: You can use the is_open() function of the file stream object to determine whether the file is opened successfully. The function will return true if the opening was successful, otherwise false.
Get the file position: You can use the tellg() function of the input stream object to get the current read position, and use the tellp() function of the output stream object to get the current write position. The value returned by these functions is a pointer to the byte offset of the current location.
Moving the file position: You can use the seekg() function of the input stream object and the seekp() function of the output stream object to move the reading or writing position. The first parameter of these functions is a pointer, specifying the byte offset of the position to move, and the second parameter specifies the relative position to move, such as ios::beg (beginning of file), ios::cur ( current position) or ios::end (end of file).
Determine the end of the file: You can use the eof() function of the input stream object to determine whether the end of the file has been reached. The function will return true if the end of the file has been reached, false otherwise.

#include <iostream>
#include <fstream>

using namespace std;

int main() {
    
    
        // 打开文件
    ofstream outfile("data.txt");
    if (!outfile.is_open()) {
    
    
        cout << "无法打开文件" << endl;
        return 1;
    }

    // 写入数据
    //outfile << "Hello, world!" << endl;
    outfile << "Hello, world!1" << endl;
    outfile << "Hello, world!1"<<endl;

    // 关闭文件
    outfile.close();

    // 打开文件
    ifstream infile("data.txt");
    if (!infile.is_open()) {
    
    
        cout << "无法打开文件" << endl;
        return 1;
    }

    // 获取文件大小
    infile.seekg(0, ios::end);
    int length = infile.tellg();
    infile.seekg(0, ios::beg);
    cout<<"长度为:"<<length<<endl;

    // 读取数据
    char* buffer = new char[length+1];
    cout<<"buffer长度为:"<<sizeof(buffer)<<endl;
    infile.read(buffer, length);
    buffer[length] = '\0';

    // 输出数据
    cout << buffer << endl;

    // 释放内存并关闭文件
    delete[] buffer;
    infile.close();

    return 0;
}

insert image description here

In practice:

http://noi.openjudge.cn/

Summarize

This series is a C++ learning series, which will introduce C++ basic grammar, basic algorithms and data structures. This article is a C++ file reading and writing application case, including related case exercises.

Guess you like

Origin blog.csdn.net/m0_38139250/article/details/130443151