1. Introduction
C++ file streaming is a tool for reading and writing files. It provides a way to interact with external files simply and efficiently. In C++, file streams mainly use of ofstream and ifstream to implement write and read files.
- ofstream (output file stream) is used to write files, which can create, open and write file contents.
- ifstream (input file stream) is used to read the content of the file, which can open and read data in the file.
File streaming operations can be in text mode or binary mode, allowing for different ways to read and write files.
C++ file streams provide many functions and methods for processing files, including opening files, reading and writing file contents, closing files, etc. In order to ensure the correct use of file streams, possible errors that may occur during file operations need to be handled.
2. Start using ofstream for file writing
Create a ofstream object to open and write files:
Contains the necessary header files:
#include <fstream>
Create ofstream object:
std::ofstream outputFile;
Open the file and write the content:
(""); // Open a file named for writing if (outputFile.is_open()) { outputFile << "Hello, World!" << std::endl; // Write string to file outputFile << "This is a sample text." << std::endl; } else { std::cout << "Failed to open the file." << std::endl; // If the file fails to open, output error message} (); // Close the file stream
After the file is successfully opened, you can use the stream insertion operator (<<) to write content to the file. Finally, remember to use the close() function to close the file stream, free up resources, and ensure that the file operation is completed. This completes the operation of creating ofstream objects and writing files.
Here are the main member functions of the ofstream class:
Member functions | describe | parameter |
---|---|---|
open() | Open the file | const char* filename, ios_base::openmode mode |
close() | Close the file | none |
is_open() | Check if the file has been successfully opened | none |
good() | Check if the file stream is in a valid state | none |
bad() | Check if the file stream is in an error state | none |
operator<< | Write data to file stream | Different types of data such as int, char, string |
tellp() | Returns the location of the current file pointer (write position) | none |
seekp() | Set the write position | streamoff off, ios_base::seekdir way |
flush() | Refresh the output buffer | none |
rdbuf() | Get the buffer pointer | none |
Among them, ios_base::openmode is an enumeration type used to specify file opening mode, including out (write), app (append), trunc (trunc and write), and ate (locate to the end of the file immediately after opening the file).
In addition to the above member functions, ofstream can also use other member functions inherited from ostream, including setf, unsetf, width, etc. for setting flags and format control.
The ofstream class is an output stream class used to write data to a file. It inherits from the ostream class, so it has all member functions of the ostream class, and also has some member functions that are unique to it.
open(): Open the file, the parameters include the file name and the opening mode.
ofstream outputFile; ("");
close(): Close the open file.
();
is_open(): Check whether the file is successfully opened.
if (outputFile.is_open()) { // The file has been successfully opened} else { // File opening failed}
good(): Check whether the file stream is in a valid state.
if (()) { // The file stream is in a valid state} else { // File stream is not in valid state}
bad(): Check whether the file stream is in an error state.
if (()) { // File stream is in an error state} else { // File stream is not in an error state}
3. Use ifstream to read files
Create an ifstream object to open and read the file:
- Contains the necessary header files:
#include <fstream>
- Create ifstream object:
std::ifstream inputFile;
- Open the file and read the content:
(""); // Open a file named for reading if (inputFile.is_open()) { std::string line; while (std::getline(inputFile, line)) { std::cout << line << std::endl; // Output each line of the file } } else { std::cout << "Failed to open the file." << std::endl; // If the file cannot be opened, output error message} (); // Close the file stream
Read the file content line by looping with the getline() function and output it to the console. Finally, don't forget to close the file stream using the close() function to ensure the read is complete.
Here are the main member functions of the ifstream class and their descriptions and parameters:
Member functions | describe | parameter |
---|---|---|
open() | Open the file | const char* filename, ios_base::openmode mode |
close() | Close the file | none |
is_open() | Check if the file has been successfully opened | none |
good() | Check if the file stream is in a valid state | none |
bad() | Check if the file stream is in an error state | none |
operator>> | Read data from file stream | Different types of data such as int, char, string |
tellg() | Returns the location of the current file pointer (read position) | none |
seekg() | Set the read position | streamoff off, ios_base::seekdir way |
peek() | View the next character, but not extract it | none |
ignore() | Ignore a certain number of characters | streamsize n = 1, int_type delim = Traits::eof() |
Among them, ios_base::openmode is an enumeration type used to specify file opening mode, including in (read), binary (binary mode), etc.
4. File opening mode
model | describe |
---|---|
in | Open the file as input, allowing the file content to be read. |
out | Open the file in output mode, allowing the file content to be written. If the file does not exist, a new file is created; if the file already exists, its length is cut to 0. |
app | Attach content at the end of the file to allow writing to the file; if the file does not exist, a new file is created. |
ate | Immediately after opening the file, locate to the end of the file. |
trunc | If the file already exists, the file length is 0 (clear the file). |
binary | Open the file in binary mode, not text mode. The file content will be read and written in binary format, rather than in text format. |
By combining different opening mode options, different ways of opening files can be implemented, including read, write, append and binary mode operations.
How to choose the opening mode in different scenarios:
-
Read the file:
- If you only need to read the contents of the file, you should select "in" mode to open the file by input.
- If you want to read the file content in binary, you can select "
in | binary
"model.
-
Write to the file:
- If you want to create a new file and write content, you should select "out" mode to open the file in output mode.
- If the file already exists and you want to overwrite the original content, you can select "out" mode.
- If you want to add content at the end of the file, you can select the "app" mode.
-
Binary file operation:
- If you need to read and write files in binary mode, you should select "binary" mode.
- When performing binary file operations, you can consider using "
in | binary
"or"out | binary
” mode, depending on whether it is a read or a write operation.
-
Ensure file security:
- If you need to clear the file content before writing the file content, you can select "out | trunc" mode to ensure that the file has been cleared before writing.
- Before appending content, you can select the "app" mode to ensure that content is appended at the end of the file.
5. Error handling
5.1. Handle errors that may occur during file opening and reading and writing
Handle errors that may occur during file opening and reading and writing by checking the status of the file stream and using exception handling.
Check the status of the stream: After opening a file or performing a read and write operation, use the member functions of the stream to check the status of the file stream. Commonly used functions include good(), bad(), fail(), and eof(). Check these statuses to determine whether the file operation is successful and take corresponding actions as needed.
Using exception handling: C++'s exception handling mechanism can be used to catch and handle errors in file operations. By using the try-catch statement in the file operation code block, it can catch possible exceptions, such as file opening failures, read and write errors, etc., and process them accordingly or report error information.
Example:
#include <iostream> #include <fstream> int main() { std::ofstream outputFile(""); try { if (!outputFile) { throw "File opening failed."; } outputFile << "Hello, World!"; if (()) { throw "Writing to file failed."; } (); } catch (const char* errorMessage) { std::cerr << "Error: " << errorMessage << std::endl; } return 0; }
By checking the status of the file stream and using exception handling, errors that may occur during file opening and reading and writing can be effectively handled, thereby ensuring the stability and security of file operations.
5.2. Use the state of the flow to detect and handle errors
The stream class of C++ provides several member functions to obtain the state of the stream, and errors can be detected and processed through these states. These status flags are usually represented as return values of member functions.
Member functions for detecting and processing flow states:
good(): Check whether the stream is in a valid state, that is, no errors have occurred. Return true to indicate that the stream is in a valid state.
bad(): Check whether the stream is in an error state. Return true to indicate that the stream is in an error state.
fail(): Check whether the stream is in a failed state, which may be due to a failure of the input/output operation, but is not a fatal error. Return true to indicate that the stream is in a failed state.
eof(): Check whether the end-of-file has been reached. Return true to indicate that the end of the file has been reached.
These status flags can help us determine specific errors that occur during the file reading and writing process and make corresponding processing. For example, when reading a file, you can check the eof() status to determine whether the end of the file has been read; when writing a file, you can check the fail() status to determine whether the write failed, etc.
Example:
#include <iostream> #include <fstream> int main() { std::ifstream inputFile(""); if (!()) { std::cerr << "Error: Failed to open the file." << std::endl; return 1; } std::string data; while (inputFile >> data) { if (()) { std::cerr << "Error: Failed to read from the file." << std::endl; break; } std::cout << data << " "; } (); if (()) { std::cerr << "Error: An unrecoverable error occurred while reading the file." << std::endl; return 1; } return 0; }
6. Binary file operation
Using binary mode to read and write files is common in C++. Binary mode is suitable for processing non-text files such as images, audio, video, etc. In binary mode, the contents of the file are read and written in its original byte form without interpreting or converting the contents.
- Open a file in binary mode: Use the ofstream or ifstream object and specify the binary mode in the open() function.
std::ofstream outputFile("", std::ios::out | std::ios::binary); std::ifstream inputFile("", std::ios::in | std::ios::binary);
- Write data to binary file: Use the write() function to write binary data to the file. The arguments to the write() function include a pointer to the data to be written and the length of the data.
int data[] = {1, 2, 3, 4, 5}; (reinterpret_cast<char*>(&data), sizeof(data));
- Read data from a binary file: Use the read() function to read binary data from a file. The parameters of the read() function include a pointer to the data to be read and the length of the data.
int data[5]; (reinterpret_cast<char*>(&data), sizeof(data));
- Close file stream: Use the close() function to close the file stream to ensure that data is written or read.
(); ();
Note: Using binary mode to read and write files requires a clear understanding of the storage and size of the data to ensure that the data is read and written correctly. At the same time, when processing binary data, you need to pay attention to avoid type conversion errors and ensure that the processing of binary data is correct.
Example:
#include <iostream> #include <fstream> struct Data { int id; double value; }; int main() { // Write binary data std::ofstream outputFile("", std::ios::out | std::ios::binary); if(outputFile.is_open()) { Data data1 = {1, 3.14}; Data data2 = {2, 6.28}; // Write data to binary file (reinterpret_cast<char*>(&data1), sizeof(data1)); (reinterpret_cast<char*>(&data2), sizeof(data2)); (); } else { std::cerr << "Failed to open the file for writing." << std::endl; return 1; } // Read binary data std::ifstream inputFile("", std::ios::in | std::ios::binary); if(inputFile.is_open()) { Data data1, data2; // Read binary data from a file (reinterpret_cast<char*>(&data1), sizeof(data1)); (reinterpret_cast<char*>(&data2), sizeof(data2)); // Output the read data std::cout << "Data 1: " << << " " << << std::endl; std::cout << "Data 2: " << << " " << << std::endl; (); } else { std::cerr << "Failed to open the file for reading." << std::endl; return 1; } return 0; }
7. Comprehensive examples
Use of ofstream and ifstream to read and write files, including text files and binary files.
#include <iostream> #include <fstream> // Structure is used to store binary file datastruct Data { int id; double value; }; int main() { // Write text file std::ofstream textOutputFile(""); if(textOutputFile.is_open()) { textOutputFile << "This is a text file." << std::endl; textOutputFile << "It is used to demonstrate text file writing." << std::endl; (); } else { std::cerr << "Failed to open the text file for writing." << std::endl; return 1; } // Read text file std::ifstream textInputFile(""); if(textInputFile.is_open()) { std::string line; while (std::getline(textInputFile, line)) { std::cout << line << std::endl; } (); } else { std::cerr << "Failed to open the text file for reading." << std::endl; return 1; } // Write to binary file std::ofstream binaryOutputFile("", std::ios::out | std::ios::binary); if(binaryOutputFile.is_open()) { Data data1 = {1, 3.14}; Data data2 = {2, 6.28}; (reinterpret_cast<char*>(&data1), sizeof(data1)); (reinterpret_cast<char*>(&data2), sizeof(data2)); (); } else { std::cerr << "Failed to open the binary file for writing." << std::endl; return 1; } // Read binary files std::ifstream binaryInputFile("", std::ios::in | std::ios::binary); if(binaryInputFile.is_open()) { Data data1, data2; (reinterpret_cast<char*>(&data1), sizeof(data1)); (reinterpret_cast<char*>(&data2), sizeof(data2)); std::cout << "Data 1: " << << " " << << std::endl; std::cout << "Data 2: " << << " " << << std::endl; (); } else { std::cerr << "Failed to open the binary file for reading." << std::endl; return 1; } return 0; }
8. Summary
It introduces C++ file streams as tools for reading and writing files, as well as the basic functions and usage of ofstream and ifstream classes.
ofstream member functions: Overwrites some common member functions of the ofstream class, including open(), close(), is_open(), good(), bad(), operator<<, etc. These functions are the key to implementing file write operations.
Use the stream insertion operator (<<) to write data to a file.
File opening modes, including read, write, append and binary modes, and how to choose the appropriate opening mode in different situations.
Handle errors that may occur in file opening and read and write operations, including using the state of the stream to detect errors and using exception handling.
Read and write files in binary mode: It introduces how to use binary mode to read and write files, including how to open files in binary mode, write data to binary files, read data from binary files, etc.
The above is the detailed content of C++'s file reading and writing through ofstream and ifstream. For more information about reading and writing of C++ ofstream and ifstream files, please follow my other related articles!