温馨提示×

C++ Linux中文件操作有哪些

小樊
53
2025-09-01 05:16:25
栏目: 编程语言

在Linux环境下,C++可以使用多种方法进行文件操作。以下是一些常用的文件操作:

1. C标准库函数

C++继承了C语言的文件操作函数,这些函数定义在<cstdio>头文件中。

  • 打开文件

    FILE* fopen(const char* filename, const char* mode);
    
  • 关闭文件

    int fclose(FILE* stream);
    
  • 读取文件

    size_t fread(void* ptr, size_t size, size_t count, FILE* stream);
    
  • 写入文件

    size_t fwrite(const void* ptr, size_t size, size_t count, FILE* stream);
    
  • 定位文件指针

    int fseek(FILE* stream, long offset, int whence);
    long ftell(FILE* stream);
    
  • 获取文件状态

    int fstat(int fd, struct stat* buf);
    

2. C++标准库中的文件流

C++提供了更高级的文件操作接口,定义在<fstream>头文件中。

  • 文件输入输出流

    • std::ifstream:用于读取文件。
    • std::ofstream:用于写入文件。
    • std::fstream:既可以读取也可以写入文件。
    std::ifstream infile("example.txt");
    std::ofstream outfile("output.txt");
    std::fstream file("data.txt", std::ios::in | std::ios::out);
    
  • 读写操作

    infile >> data; // 读取数据
    outfile << data; // 写入数据
    
  • 文件状态检查

    if (infile.is_open()) {
        // 文件已打开
    }
    

3. POSIX API

POSIX(Portable Operating System Interface)是一套标准的操作系统接口,Linux系统广泛支持。

  • 打开文件

    int open(const char* path, int flags);
    
  • 关闭文件

    int close(int fd);
    
  • 读取文件

    ssize_t read(int fd, void* buf, size_t count);
    
  • 写入文件

    ssize_t write(int fd, const void* buf, size_t count);
    
  • 定位文件指针

    off_t lseek(int fd, off_t offset, int whence);
    

4. 其他高级功能

  • 内存映射文件:使用mmap系统调用将文件映射到内存中,提高读写效率。
  • 异步I/O:使用aio系列函数进行异步文件操作。
  • 文件锁:使用fcntl系统调用对文件进行加锁和解锁操作。

示例代码

以下是一个简单的示例,展示如何使用C++标准库中的文件流进行文件读写:

#include <iostream>
#include <fstream>
#include <string>

int main() {
    // 写入文件
    std::ofstream outfile("example.txt");
    if (outfile.is_open()) {
        outfile << "Hello, World!" << std::endl;
        outfile.close();
    } else {
        std::cerr << "Unable to open file for writing." << std::endl;
    }

    // 读取文件
    std::ifstream infile("example.txt");
    if (infile.is_open()) {
        std::string line;
        while (getline(infile, line)) {
            std::cout << line << std::endl;
        }
        infile.close();
    } else {
        std::cerr << "Unable to open file for reading." << std::endl;
    }

    return 0;
}

通过这些方法,你可以在Linux环境下使用C++进行各种文件操作。选择合适的方法取决于你的具体需求和偏好。

0