阅读量:3
在Linux下,C++可以使用多种方式进行文件操作。以下是一些常用的文件操作方法:
1. 使用标准库 和
fopen(): 打开文件。fclose(): 关闭文件。fread(): 从文件读取数据。fwrite(): 向文件写入数据。fseek(): 移动文件指针。ftell(): 获取文件指针位置。fstat(): 获取文件状态信息。remove(): 删除文件。rename(): 重命名文件。
#include
#include
int main() {
FILE *file = fopen("example.txt", "r");
if (file == nullptr) {
std::cerr << "Failed to open file!" << std::endl;
return 1;
}
char buffer[1024];
size_t bytesRead = fread(buffer, 1, sizeof(buffer), file);
if (bytesRead > 0) {
std::cout << "Read " << bytesRead << " bytes from file." << std::endl;
}
fclose(file);
return 0;
}
2. 使用标准库
std::ifstream: 输入文件流。std::ofstream: 输出文件流。std::fstream: 输入输出文件流。
#include
#include
int main() {
std::ifstream inputFile("example.txt");
if (!inputFile.is_open()) {
std::cerr << "Failed to open input file!" << std::endl;
return 1;
}
std::string line;
while (std::getline(inputFile, line)) {
std::cout << line << std::endl;
}
inputFile.close();
return 0;
}
3. 使用 POSIX API
open(): 打开文件。close(): 关闭文件。read(): 从文件读取数据。write(): 向文件写入数据。lseek(): 移动文件指针。stat(): 获取文件状态信息。remove(): 删除文件。rename(): 重命名文件。
#include
#include
#include
int main() {
int fd = open("example.txt", O_RDONLY);
if (fd == -1) {
std::cerr << "Failed to open file!" << std::endl;
return 1;
}
char buffer[1024];
ssize_t bytesRead = read(fd, buffer, sizeof(buffer));
if (bytesRead > 0) {
std::cout << "Read " << bytesRead << " bytes from file." << std::endl;
}
close(fd);
return 0;
}
4. 使用 C++17 的
std::filesystem::create_directory(): 创建目录。std::filesystem::remove(): 删除文件或目录。std::filesystem::rename(): 重命名文件或目录。std::filesystem::path: 处理文件路径。
#include
#include
namespace fs = std::filesystem;
int main() {
if (!fs::exists("example.txt")) {
std::cout << "File does not exist." << std::endl;
return 1;
}
if (fs::remove("example.txt")) {
std::cout << "File removed successfully." << std::endl;
} else {
std::cerr << "Failed to remove file." << std::endl;
}
return 0;
}
注意事项
- 使用文件操作时,确保文件路径正确。
- 处理文件指针和文件描述符时要小心,避免资源泄漏。
- 在多线程环境中,注意文件的并发访问问题。
通过这些方法,你可以在Linux下使用C++进行各种文件操作。
以上就是关于“C++在Linux下的文件操作有哪些”的相关介绍,筋斗云是国内较早的云主机应用的服务商,拥有10余年行业经验,提供丰富的云服务器、租用服务器等相关产品服务。云服务器资源弹性伸缩,主机vCPU、内存性能强悍、超高I/O速度、故障秒级恢复;电子化备案,提交快速,专业团队7×24小时服务支持!
简单好用、高性价比云服务器租用链接:https://www.jindouyun.cn/product/cvm