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

   2024-09-30 8500
核心提示:在C++中,你可以使用fstream库和truncate()函数来截断文件#includeiostream#include fstream#include fcntl.h// for open()#incl

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

#include<iostream>#include <fstream>#include <fcntl.h>    // for open()#include <unistd.h>   // for truncate()#include <sys/types.h> // for off_tint 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上,你需要使用其他方法来截断文件。

 
举报打赏
 
更多>同类物流大全
推荐图文
推荐物流大全
点击排行

网站首页  |  关于我们  |  联系方式 | 网站留言    |  赣ICP备2021007278号