溫馨提示×

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

c++
小樊
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 << " 字節(jié)。"<< std::endl;
    return 0;
}

這個示例程序首先打開一個名為example.txt的文件,然后使用truncate()函數將其大小截斷為5字節(jié)。請確保在運行此程序之前創(chuàng)建一個名為example.txt的文件,并填寫一些內容。運行此程序后,example.txt的大小應該會被截斷為5字節(jié)。

注意:這個示例程序需要在支持POSIX的系統(tǒng)上運行,如Linux或macOS。在Windows上,你需要使用其他方法來截斷文件。

0