C++ File Operation Knowledge Summary

Posted by always_confused on Mon, 10 Jan 2022 18:28:27 +0100

Catalog

  1. Basic File Concepts
  2. File I/O
  3. File Order Read-Write and Random File Read-Write
  4. Opening and Closing of Files
  5. Text File Processing
  6. get(), getline(), put() function
  7. Other operations

1. Basic Document Concepts

The file can be viewed as a continuous set of strings that have no size
Strings exist as streams, and files can also be viewed as a collection of streams, called streaming files
_Files can be viewed as a format for storing information together, usually on the external storage media of a computer
Using files is a bit:
1) Files enable a program to process different input data and produce corresponding output results
2) The use of files can facilitate users and improve the efficiency of the computer
3) Files can be used without memory size limitations

I I. Document I/O

In the C++ standard library, there are rich classes for file I/O operations, each of which is based on an abstract class, which then derives a specific implementation class.
The operation of files in C++ is divided into the following steps:
1 Create File Flow Object
2 Open or create a file
3 Read and write
4 Close the file
Three stream classes for file I/O operations
1 fstream (input output file stream)
2 ifstream (input file stream)
3 ofsream (output file stream)
All three classes are contained in the fstream header file. Programs operate on files and must include the header file.
If the ifstream object is reused, be careful to call the clear function before using it, otherwise an error will occur.

fstream case

#include <iostream>
#include <string>
#include <fstream>
using namespace std;
//Under the current project directory test06, set up com.txt
void fstreamEx()
{
	char buffer[256];
	fstream out;
	out.open("com.txt", ios::in);
	cout << "com.txt The contents are as follows:"<< endl;
	while(!out.eof())//eof end of file to determine whether to end the file
	{
		//getline(char*, int, char) means that the line reaches 256 characters or ends when a new line character is encountered
		out.getline(buffer, 256, '\n');
		cout << buffer << endl;
	}
	out.close();
	//cin.get() is used to read the return key, if there is no line
	//The output disappears in a flash
	//cin.get();
}
void main()
{
	fstreamEx();
	system("pause");
}

ifstream case

#include <iostream>
#include <string>
#include <fstream>
using namespace std;
//Test ifstream
int CountLines(char *filename)
{
	ifstream readFile;
	int n = 0;
	char line[512];
	string temp;
	//ios::in means to read the file read-only
	readFile.open(filename, ios::in);
	//File open failed, return true
	if(readFile.fail())
	{
		return 0;
	}
	else//File Exists
	{
		while(getline(readFile, temp))
		{
			n++;
		}
		return n;
	}
	readFile.close();
}

void ifstreamEx()
{
	cout << "com.txt Number of rows: " << CountLines("com.txt") << endl;
}

void main()
{
	ifstreamEx();
	system("pause");
}

ofstream case

#include <iostream>
#include <string>
#include <fstream>
using namespace std;

void ofstreamEx()
{
	ofstream in;
	//ios::trunc means to empty the file before opening it
	//Create a file if it does not exist due to writing
	in.open("com.txt", ios::trunc);
	int i;
	char a = 'a';
	for(i = 1; i <= 26; i++)
	{
		if(i < 10)
		{
			in << "0" << i << "\t" << a << "\n";
			a++;
		}
		else
		{
			in << i << "\t" << a << "\n";
			a++;
		}
	}
	in.close();
}

void main()
{
	ofstreamEx();
	system("pause");
}

3. Reading and Writing Files in Order and Reading and Writing Random Files

Sequential reading and writing:
In C++ files, each record is stored one after another. If you want to find a record, you must read the record of the file one by one from the beginning of the file until you find the location of the record.
Read and write random files:
Random files have a record number for each record. When reading and writing data, you can read and write the data as long as the record number is specified.

Random File Read-Write Cases

#include <iostream>
#include <string>
#include <fstream>
using namespace std;

int CountLines(char *filename)
{
	ifstream readFile;
	int n = 0;
	string tmp;

	readFile.open(filename, ios::in);
	if(readFile.fail())
	{
		return 0;
	}
	else
	{
		while(getline(readFile, tmp))
		{
			n++;
		}
		return n;
	}

	readFile.close();
}

string ReadLine(char *filename, int line)
{
	int lines, i = 0;
	string temp;
	fstream file;
	file.open(filename, ios::in);
	lines = CountLines(filename);
	if(line <= 0)
	{
		return "error 1, Wrong number of rows, cannot be 0 or negative";
	}
	if(file.fail())
	{
		return "error 2, file does not exist.";
	}
	if(line > lines)
	{
		return "error 3, Lines exceed file length";
	}
	while(getline(file, temp) && i < line - 1)
	{
		i++;
	}
	file.close();
	return temp;
}

void test01()
{
	int l;
	char filename[256];
	cout << "Please enter a file name: " << endl;
	cin >> filename;
	cout << "Please enter the number of rows to read: " << endl;
	cin >> l;
	cout << ReadLine(filename, l) << endl;
}

void main()
{
	test01();
	system("pause");
}

4. Opening and Closing of Documents

In C++, to input and output files, you must create a stream to associate the stream with the file in order to operate on the file and close the file when finished.

File Opening

1) open() member function in fstream class
Open member function in fstream class to open file. The function prototype is:
void open(const char* filename, int mode, int access);
The parameters have the following meanings:
filename: The name of the file to open
mode: how to open the file
access: properties of the open file
The way files are opened is defined in the class ios, which is the base class for all streaming IO classes. Common values are as follows:
ios::app: Open the file by appending
ios::ate:File opens to the end of the file, and ios:app contains this property
ios::binary: Open the file in binary mode, default mode is text mode
ios::in: File is opened as input
ios::out: The file has been opened as output
ios::nocreate: No file is created, so when the file does not exist, it fails to open
ios::noreplace: Does not overwrite the file, so opening the file fails when it exists
ios::trunc: If the file exists, set the file length to 0.
These attributes can be joined using OR, such as ios::out| ios::binary
Property values for open files:
0 Normal file, open access
1 Read-only file
2 Implicit Files
3 System Files
Default Open Mode:
If no open mode parameter is specified, the compiler will use the default value
fstream has no default value
ifstream std::ios::in
ofstream std::ios::out | std::ios::trunk

Closing of Files

1 When the file read and write operation is complete, the file must be closed to make the file accessible again.
2 Closing a file requires calling the member function close(), which is responsible for draining data from the cache and closing the file.
3 Close format: void close(); Once this function is called, the original stream object can be used to open other files, which can be accessed by other processes again.
4 To prevent the open file from being contacted when the stream object is destroyed, the destructor will automatically call the close function.

V. Text File Processing

Text files are processed with ASCII and can be processed with character processing software. Text files are easy to read and write. Use the insert operator < to output to the file and the disjunctive operator >> to input from the file.

Write variables to file

void writeFile()
{
	ofstream outfile;
	outfile.open("a.txt");//
	outfile << "Sweat drips into the soil on weed day afternoon";
	outfile.close();
}

Write variables to the end of the file

void writeAppendFile()
{
	ofstream outfile;
	outfile.open("a.txt", ios::out | ios::app);
	outfile << "Who knows that every grain works hard at lunch";
	outfile.close();	
}

Read variables from a text file

void readFile()
{
	ifstream infile;
	char value;
	infile.open("com.txt");
	if(infile.is_open())
	{
         //infile >> value
		while(infile.get(value))
		{
			cout << value;
		}
	}
	cout << endl;
	infile.close();
}

6. get(), getline(), put() functions

get()

The get function is a member function of the ifstream class that reads a character of the class's object and returns it as a call function. The get function automatically reads the next character backwards until it encounters the end of the file and returns EOF as the end of the file.

void testGet()
{
	ifstream infile;
	char value;
	infile.open("a.txt");
	if(infile.is_open())
	{
		while(infile.get(value))
		{
			cout << value;
		}
	}
	cout << endl;
	infile.close();
}

getline(str, n, '\n')

Read characters from a file into the string str until n-1 characters are read or'\n'is encountered

void testGetLine()
{
	char buffer[256];
	ifstream infile("com.txt");
	if(!infile.is_open())
	{
		cout << "error opening file";
		exit(1);
	}

	while(!infile.eof())
	{
		infile.getline(buffer, 100);
		cout << buffer << endl;
	}
}

getline(str, n, '\n')

The put function is used to output the stream ofstream, outputting a single character

void testPut()
{
	ofstream out("a.txt");//Create a file
	out.put('A');
	out.put('B');
	out.close();
}

7. Other Operations

get(c) Reads a character from a file, and if -1 is returned, reads to the end of the file.
eof() returns true if it reaches the end of the file, otherwise it returns false.
remove(const char* name), delete the file, return true successfully, otherwise return false
peek(): Find the next character, but do not remove it from the file

Topics: C C++