C++通用业务标准库中常用接口函数总结
📚 目录
- 线程支持 (
<thread>) - 时间库 (
<chrono>) - 字符串操作 (
<string>) - 文件流操作 (
<fstream>) - 时间函数 (
<ctime>) - 输入输出格式化 (
<iomanip>) - 字符串流 (
<sstream>) - 综合示例
线程支持 (<thread>)
C++11/14/17 核心接口
cpp
// 线程管理
std::thread // 线程类
thread.join() // 等待线程结束
thread.detach() // 分离线程
thread.joinable() // 检查线程是否可join
thread.get_id() // 获取线程ID
thread.native_handle() // 获取原生线程句柄
// 当前线程操作
std::this_thread::sleep_for(duration) // 休眠指定时长
std::this_thread::sleep_until(time_point) // 休眠到指定时间点
std::this_thread::yield() // 让出CPU时间片
std::this_thread::get_id() // 获取当前线程ID
// 硬件信息
std::thread::hardware_concurrency() // 获取硬件支持的并发线程数
C++20 新增特性
cpp
#include <stop_token>
#include <semaphore>
#include <latch>
#include <barrier>
// 可停止线程
std::jthread // 自动join的线程,支持停止令牌
std::stop_token // 停止令牌
std::stop_source // 停止源
std::stop_callback // 停止回调
// 同步原语
std::counting_semaphore // 计数信号量
std::binary_semaphore // 二进制信号量
std::latch // 一次性屏障
std::barrier // 可重复使用屏障
基本用法
cpp
#include <thread>
#include <iostream>
void worker(int id) {
for (int i = 0; i < 3; ++i) {
std::cout << "线程 " << id << " 工作 " << i << std::endl;
std::this_thread::sleep_for(std::chrono::milliseconds(100));
}
}
int main() {
std::thread t1(worker, 1);
std::thread t2(worker, 2);
t1.join();
t2.join();
return 0;
}
时间库 (<chrono>)
C++11/14/17 核心接口
cpp
// 时钟
std::chrono::system_clock // 系统时钟(可调整)
std::chrono::steady_clock // 稳定时钟(单调递增)
std::chrono::high_resolution_clock // 高精度时钟
// 时间点
clock::now() // 获取当前时间点
// 时间段
std::chrono::duration // 时间段模板类
std::chrono::hours, minutes, seconds, milliseconds, microseconds, nanoseconds
// 时间操作
std::chrono::duration_cast<To>(duration) // 时间单位转换
std::chrono::time_point_cast<To>(time_point) // 时间点精度转换
// C++14 字面量
using namespace std::chrono_literals;
auto time = 5s; // 5秒
auto time = 100ms; // 100毫秒
auto time = 24h; // 24小时
C++20 新增特性
cpp
#include <chrono>
// 日历和时区支持
std::chrono::year, month, day
std::chrono::year_month_day
std::chrono::sys_time, local_time, zoned_time
// 日期字面量
using namespace std::chrono;
auto d = 2023y/December/25d; // 2023年12月25日
// 新的时钟
std::chrono::utc_clock // UTC时钟
std::chrono::tai_clock // TAI时钟
std::chrono::gps_clock // GPS时钟
std::chrono::file_clock // 文件时钟
// 格式化支持
std::format("{:%Y-%m-%d %H:%M:%S}", system_clock::now())
基本用法
cpp
#include <chrono>
#include <thread>
#include <iostream>
// 计时示例
auto start = std::chrono::steady_clock::now();
std::this_thread::sleep_for(150ms);
auto end = std::chrono::steady_clock::now();
auto duration = std::chrono::duration_cast<std::chrono::milliseconds>(end - start);
std::cout << "耗时: " << duration.count() << " 毫秒" << std::endl;
// C++20 日期操作
#if __cplusplus >= 202002L
auto today = std::chrono::floor<std::chrono::days>(std::chrono::system_clock::now());
std::chrono::year_month_day ymd{today};
std::cout << "今天: " << static_cast<int>(ymd.year()) << "-"
<< static_cast<unsigned>(ymd.month()) << "-"
<< static_cast<unsigned>(ymd.day()) << std::endl;
#endif
字符串操作 (<string>)
C++11/14/17 核心接口
cpp
// 构造和赋值
std::string str; // 默认构造
std::string str("hello"); // C字符串构造
std::string str(other_str); // 拷贝构造
std::string str(std::move(other_str)); // 移动构造(C++11)
str = "world"; // 赋值
// 容量操作
str.size() / str.length() // 字符串长度
str.empty() // 是否为空
str.capacity() // 容量
str.reserve(size) // 预留空间
str.shrink_to_fit() // 收缩到合适大小(C++11)
// 元素访问
str[index] // 访问指定位置字符
str.at(index) // 带边界检查的访问
str.front() // 首字符(C++11)
str.back() // 尾字符(C++11)
str.c_str() // 返回C风格字符串
str.data() // 返回字符数组
// 修改操作
str.append("world") // 追加字符串
str.push_back('!') // 追加字符
str.insert(pos, "text") // 插入字符串
str.erase(pos, count) // 删除字符
str.clear() // 清空字符串
str.replace(pos, count, "new") // 替换内容
// 字符串操作
str.substr(pos, count) // 获取子串
str.find("pattern") // 查找子串
str.compare(other_str) // 比较字符串
str.starts_with(prefix) // C++20
str.ends_with(suffix) // C++20
str.contains(substr) // C++23
// 数值转换
std::to_string(123) // 数值转字符串(C++11)
std::stoi("123") // 字符串转int(C++11)
std::stol("123") // 字符串转long(C++11)
std::stoll("123") // 字符串转long long(C++11)
std::stof("1.23") // 字符串转float(C++11)
std::stod("1.23") // 字符串转double(C++11)
C++17/20 新增特性
cpp
// C++17
std::string_view // 字符串视图,轻量级只读字符串
std::pmr::string // 多态分配器字符串
// C++20
str.starts_with(prefix) // 检查前缀
str.ends_with(suffix) // 检查后缀
str.contains(char_or_str) // 检查是否包含(C++23)
// C++20 格式化
std::format("Hello, {}!", "World") // 格式化字符串
std::format("{:.2f}", 3.14159) // 浮点数格式化
文件流操作 (<fstream>)
C++11/14/17 核心接口
cpp
// 文件流类
std::ifstream // 输入文件流(读取)
std::ofstream // 输出文件流(写入)
std::fstream // 文件流(读写)
// 文件打开模式
std::ios::in // 读模式
std::ios::out // 写模式
std::ios::app // 追加模式
std::ios::binary // 二进制模式
std::ios::trunc // 截断模式
std::ios::ate // 打开时定位到文件末尾
// 文件操作
file.open("filename", mode) // 打开文件
file.close() // 关闭文件
file.is_open() // 检查文件是否打开
// 状态检查
file.good() // 流状态正常
file.eof() // 到达文件末尾
file.fail() // 操作失败
file.bad() // 严重错误
file.rdstate() // 获取状态标志
file.clear() // 清除状态标志
// 读取操作
file >> variable // 格式化读取
std::getline(file, str) // 读取一行
file.get() // 读取一个字符
file.read(buffer, size) // 读取二进制数据
file.getline(buffer, size) // 读取一行到字符数组
file.ignore(n, delim) // 忽略字符
// 写入操作
file << data // 格式化写入
file.put(ch) // 写入一个字符
file.write(data, size) // 写入二进制数据
file.flush() // 刷新缓冲区
// 文件定位
file.tellg() // 获取读取位置
file.tellp() // 获取写入位置
file.seekg(pos) // 设置读取位置
file.seekp(pos) // 设置写入位置
file.seekg(offset, direction) // 相对位置移动
C++17 文件系统库
cpp
#include <filesystem>
namespace fs = std::filesystem;
// 路径操作
fs::path p = "dir/file.txt";
p.filename() // 获取文件名
p.extension() // 获取扩展名
p.parent_path() // 获取父路径
// 文件操作
fs::exists(path) // 检查路径是否存在
fs::is_directory(path) // 是否是目录
fs::is_regular_file(path) // 是否是普通文件
fs::file_size(path) // 获取文件大小
fs::last_write_time(path) // 获取最后修改时间
// 目录操作
fs::create_directory(path) // 创建目录
fs::remove(path) // 删除文件或空目录
fs::remove_all(path) // 递归删除
fs::copy(from, to) // 复制文件
fs::rename(from, to) // 重命名
// 遍历目录
for (auto& entry : fs::directory_iterator(path)) {
std::cout << entry.path() << std::endl;
}
时间函数 (<ctime>)
传统C风格时间函数
cpp
// 时间获取
std::time_t timestamp = std::time(nullptr) // 获取当前时间戳
std::tm* local_time = std::localtime(×tamp) // 时间戳转本地时间
std::tm* utc_time = std::gmtime(×tamp) // 时间戳转UTC时间
std::time_t new_time = std::mktime(&tm) // 时间结构转时间戳
// 时间格式化
char buffer[100];
std::strftime(buffer, sizeof(buffer), format, &tm) // 格式化时间为字符串
char* str = std::asctime(&tm) // 时间结构转字符串
char* str = std::ctime(×tamp) // 时间戳转字符串
// 时间结构tm成员
tm.tm_sec // 秒 [0-59]
tm.tm_min // 分 [0-59]
tm.tm_hour // 时 [0-23]
tm.tm_mday // 日 [1-31]
tm.tm_mon // 月 [0-11]
tm.tm_year // 年(从1900开始)
tm.tm_wday // 星期 [0-6]
tm.tm_yday // 年中的天数 [0-365]
tm.tm_isdst // 夏令时标志
常用格式说明符
cpp
%Y // 四位年份
%y // 两位年份
%m // 月份 [01-12]
%d // 日期 [01-31]
%H // 24小时制 [00-23]
%I // 12小时制 [01-12]
%M // 分钟 [00-59]
%S // 秒 [00-59]
%p // AM/PM
%F // %Y-%m-%d 格式
%T // %H:%M:%S 格式
输入输出格式化 (<iomanip>)
C++11/14/17 核心接口
cpp
// 字段宽度和对齐
std::setw(width) // 设置字段宽度
std::setfill(ch) // 设置填充字符
std::left // 左对齐
std::right // 右对齐
std::internal // 内部对齐(符号左对齐,数值右对齐)
// 数值格式
std::setprecision(n) // 设置浮点数精度
std::fixed // 固定小数格式
std::scientific // 科学计数法格式
std::hex // 十六进制
std::dec // 十进制
std::oct // 八进制
std::showbase // 显示数值基数
std::noshowbase // 不显示数值基数
std::showpoint // 总是显示小数点
std::boolalpha // 布尔值显示为true/false
std::noboolalpha // 布尔值显示为1/0
std::showpos // 显示正数的+号
std::uppercase // 大写输出(科学计数法、十六进制)
// 其他格式
std::setbase(base) // 设置数值基数(8,10,16)
std::quoted(str) // 引用字符串(C++14)
std::put_time(&tm, format) // 格式化时间输出(C++11)
C++20 新增特性
cpp
// C++20 格式化库 (需要包含 <format>)
#include <format>
std::format("Hello, {}!", "World") // 位置参数
std::format("{1} {0}", "World", "Hello") // 索引参数
std::format("{:.2f}", 3.14159) // 浮点数格式化
std::format("{:>10}", "text") // 对齐
std::format("{:x}", 255) // 十六进制
// 输出格式化
std::cout << std::format("The answer is {}.", 42) << std::endl;
字符串流 (<sstream>)
C++11/14/17 核心接口
cpp
// 字符串流类
std::stringstream // 字符串流(读写)
std::istringstream // 输入字符串流(读取)
std::ostringstream // 输出字符串流(写入)
// 基本操作
ss.str() // 获取字符串内容
ss.str("new content") // 设置字符串内容
ss.view() // 返回string_view (C++20)
// 状态操作
ss.clear() // 清除状态标志
ss.rdstate() // 获取状态
// 与iostream相同的操作
ss << data // 写入数据
ss >> variable // 读取数据
std::getline(ss, str) // 读取一行
基本用法
cpp
#include <sstream>
#include <string>
#include <iostream>
// 字符串分割
std::string data = "apple,banana,cherry";
std::istringstream iss(data);
std::string token;
while (std::getline(iss, token, ',')) {
std::cout << token << std::endl;
}
// 构建复杂字符串
std::ostringstream oss;
oss << "姓名: " << "张三" << ", 年龄: " << 25;
std::string result = oss.str();
std::cout << result << std::endl;
// 类型转换
std::string number_str = "123.45";
std::istringstream num_iss(number_str);
double value;
num_iss >> value;
std::cout << "转换后的数值: " << value << std::endl;
综合示例
多线程文件处理器
cpp
#include <thread>
#include <fstream>
#include <sstream>
#include <chrono>
#include <string>
#include <vector>
#include <filesystem>
#include <iostream>
#include <iomanip>
class FileProcessor {
private:
std::string input_dir;
std::string output_dir;
public:
FileProcessor(const std::string& in_dir, const std::string& out_dir)
: input_dir(in_dir), output_dir(out_dir) {}
void processFiles() {
namespace fs = std::filesystem;
// 确保输出目录存在
fs::create_directories(output_dir);
// 遍历输入目录
for (const auto& entry : fs::directory_iterator(input_dir)) {
if (entry.is_regular_file() && entry.path().extension() == ".txt") {
processSingleFile(entry.path());
}
}
}
private:
void processSingleFile(const std::filesystem::path& file_path) {
std::ifstream input_file(file_path);
if (!input_file.is_open()) {
std::cerr << "无法打开文件: " << file_path << std::endl;
return;
}
// 创建输出文件路径
auto output_path = std::filesystem::path(output_dir) /
file_path.filename().replace_extension(".processed.txt");
std::ofstream output_file(output_path);
if (!output_file.is_open()) {
std::cerr << "无法创建输出文件: " << output_path << std::endl;
return;
}
// 处理文件内容
std::string line;
int line_count = 0;
auto start_time = std::chrono::steady_clock::now();
while (std::getline(input_file, line)) {
if (!line.empty()) {
// 简单的处理:转换为大写并添加行号
std::ostringstream processed_line;
processed_line << std::setw(4) << ++line_count << ": ";
for (char c : line) {
processed_line << static_cast<char>(std::toupper(c));
}
output_file << processed_line.str() << std::endl;
// 模拟处理时间
std::this_thread::sleep_for(std::chrono::milliseconds(1));
}
}
auto end_time = std::chrono::steady_clock::now();
auto duration = std::chrono::duration_cast<std::chrono::milliseconds>(
end_time - start_time);
std::cout << "处理完成: " << file_path.filename()
<< " (" << line_count << " 行, 耗时 "
<< duration.count() << "ms)" << std::endl;
input_file.close();
output_file.close();
}
};
// 日志记录器
class Logger {
public:
enum Level { INFO, WARNING, ERROR };
static void log(Level level, const std::string& message) {
auto now = std::chrono::system_clock::now();
auto time_t = std::chrono::system_clock::to_time_t(now);
std::ostringstream log_entry;
log_entry << std::put_time(std::localtime(&time_t), "%Y-%m-%d %H:%M:%S");
switch (level) {
case INFO: log_entry << " [INFO] "; break;
case WARNING: log_entry << " [WARN] "; break;
case ERROR: log_entry << " [ERROR] "; break;
}
log_entry << message;
std::cout << log_entry.str() << std::endl;
// 同时写入日志文件
std::ofstream log_file("application.log", std::ios::app);
if (log_file.is_open()) {
log_file << log_entry.str() << std::endl;
log_file.close();
}
}
};
int main() {
Logger::log(Logger::INFO, "应用程序启动");
// 创建工作目录
std::filesystem::create_directories("input");
std::filesystem::create_directories("output");
// 创建示例文件
std::ofstream test_file("input/example1.txt");
test_file << "这是第一个示例文件\n包含多行文本\n用于演示文件处理功能";
test_file.close();
test_file.open("input/example2.txt");
test_file << "第二个示例文件\n更多的文本内容\n处理线程演示";
test_file.close();
// 创建文件处理器
FileProcessor processor("input", "output");
// 在线程中处理文件
std::thread file_thread([&processor]() {
Logger::log(Logger::INFO, "文件处理线程启动");
processor.processFiles();
Logger::log(Logger::INFO, "文件处理线程完成");
});
// 主线程可以执行其他任务
Logger::log(Logger::INFO, "主线程继续执行其他任务");
for (int i = 0; i < 5; ++i) {
std::this_thread::sleep_for(std::chrono::seconds(1));
Logger::log(Logger::INFO, "主线程工作中... " + std::to_string(i + 1));
}
// 等待文件处理线程完成
file_thread.join();
Logger::log(Logger::INFO, "应用程序结束");
return 0;
}
编译说明
C++17 编译:
bash
g++ -std=c++17 -o file_processor main.cpp -lpthread
C++20 编译:
bash
g++ -std=c++20 -o file_processor main.cpp -lpthread
主要适用于入门、初级、中级开发者通用基础业务,且主要以单线程操作举例。
10.24祝各位友友们: 生活如同长江水,一顺百顺发发发!
该综合示例展示了如何结合使用多个C++标准库组件来实现一个完整的文件处理应用程序,包括多线程、文件操作、字符串处理、时间管理和日志记录等功能。