温馨提示×

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

c++
小樊
115
2024-09-10 18:39:13
栏目: 编程语言
C++开发者专用服务器限时活动,0元免费领,库存有限,领完即止! 点击查看>>

在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上,你需要使用其他方法来截断文件。

亿速云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>

推荐阅读:C++ ifndef为何在头文件中使用

0