V信公众号: 程序员架构笔记
在C++中,文件的打开、关闭、读写操作以及二进制文件与文本文件的处理是常见的文件操作任务。以下是这些操作的详细说明和示例代码。
1. 文件的打开与关闭
在C++中,文件操作通常使用fstream
、ifstream
和ofstream
类。这些类分别用于文件的输入输出、仅输入和仅输出操作。
打开文件
-
使用
open()
函数打开文件。 -
可以指定文件的打开模式,如
ios::in
(读)、ios::out
(写)、ios::app
(追加)、ios::binary
(二进制模式)等。
关闭文件
-
使用
close()
函数关闭文件。
#include <fstream>
#include <iostream>
int main() {
std::ofstream outFile;
outFile.open("example.txt", std::ios::out); // 打开文件用于写入
if (outFile.is_open()) {
outFile << "Hello, World!" << std::endl; // 写入数据
outFile.close(); // 关闭文件
} else {
std::cerr << "Failed to open file!" << std::endl;
}
return 0;
}
2. 文件的读写操作
写入文件
-
使用
<<
操作符将数据写入文件。
读取文件
-
使用
>>
操作符或getline()
函数从文件中读取数据。
#include <fstream>
#include <iostream>
#include <string>
int main() {
// 写入文件
std::ofstream outFile("example.txt");
if (outFile.is_open()) {
outFile << "Hello, World!" << std::endl;
outFile << "This is a test file." << std::endl;
outFile.close();
} else {
std::cerr << "Failed to open file for writing!" << std::endl;
}
// 读取文件
std::ifstream inFile("example.txt");
std::string line;
if (inFile.is_open()) {
while (std::getline(inFile, line)) {
std::cout << line << std::endl;
}
inFile.close();
} else {
std::cerr << "Failed to open file for reading!" << std::endl;
}
return 0;
}
3. 二进制文件与文本文件的处理
文本文件
-
文本文件以可读的字符形式存储数据。
-
使用
<<
和>>
操作符进行读写。
二进制文件
-
二进制文件以二进制形式存储数据,通常用于存储非文本数据(如图像、音频等)。
-
使用
read()
和write()
函数进行读写。
#include <fstream>
#include <iostream>
struct Data {
int id;
char name[20];
};
int main() {
// 写入二进制文件
Data data = {1, "Alice"};
std::ofstream outFile("data.bin", std::ios::binary);
if (outFile.is_open()) {
outFile.write(reinterpret_cast<char*>(&data), sizeof(data));
outFile.close();
} else {
std::cerr << "Failed to open binary file for writing!" << std::endl;
}
// 读取二进制文件
Data readData;
std::ifstream inFile("data.bin", std::ios::binary);
if (inFile.is_open()) {
inFile.read(reinterpret_cast<char*>(&readData), sizeof(readData));
inFile.close();
std::cout << "ID: " << readData.id << ", Name: " << readData.name << std::endl;
} else {
std::cerr << "Failed to open binary file for reading!" << std::endl;
}
return 0;
}
总结
-
文件的打开与关闭:使用
open()
和close()
函数。 -
文件的读写操作:使用
<<
、>>
、getline()
、read()
和write()
函数。 -
二进制文件与文本文件的处理:文本文件使用字符流操作,二进制文件使用二进制流操作。