c++

如何在C++中使用truncate截断文件

小樊
83
2024-09-10 18:39:13
栏目: 编程语言

在C++中,你可以使用fstream库和truncate()函数来截断文件

#include<iostream>
#include <fstream>
#include <fcntl.h>    // for open()
#include <unistd.h>   // for truncate()
#include <sys/types.h> // for off_t

int main() {
    std::string file_name = "example.txt";
    off_t new_size = 5; // 新的文件大小

    // 打开文件
    int fd = open(file_name.c_str(), O_RDWR);
    if (fd == -1) {
        std::cerr << "无法打开文件: "<< file_name<< std::endl;
        return 1;
    }

    // 截断文件
    if (truncate(file_name.c_str(), new_size) == -1) {
        std::cerr << "无法截断文件: "<< file_name<< std::endl;
        close(fd);
        return 1;
    }

    // 关闭文件
    close(fd);

    std::cout << "文件 "<< file_name << " 已成功截断为 "<< new_size << " 字节。"<< std::endl;
    return 0;
}

这个示例程序首先打开一个名为example.txt的文件,然后使用truncate()函数将其大小截断为5字节。请确保在运行此程序之前创建一个名为example.txt的文件,并填写一些内容。运行此程序后,example.txt的大小应该会被截断为5字节。

注意:这个示例程序需要在支持POSIX的系统上运行,如Linux或macOS。在Windows上,你需要使用其他方法来截断文件。

0
看了该问题的人还看了