簡體   English   中英

從C程序切碎並刪除linux中的文件

[英]shred and remove files in linux from a C program

我想在刪除文件之前將C程序生成的一些臨時文件切碎。

目前我正在使用

system("shred /tmp/datafile");
system("rm /tmp/datafile");

從我的程序中,但是我認為最好的方法不是調用system函數(如果我錯了,請更正我..)。還有其他方法可以做到嗎? 如何從代碼本身內切碎文件? 圖書館,還是什么? 另外,關於刪除部分, 這個答案好嗎?

請問為什么您認為這不是實現此目標的最佳方法? 如果確實有必要不可撤消地破壞文件內容,對我來說這似乎是一個不錯的解決方案。

這種方式的優點是:

  • 該程序已經存在(因此開發速度更快);
  • 該程序已被信任。

第二點很重要。 可能誇大了精心清理文件的必要性(彼得·古特曼(Peter Gutmann,在相關Wikipedia頁面上引用的話中,已將其方法的某些用法描述為“ voodoo”)),但這並不重要:在任何安全上下文中,預先存在的工具幾乎總是比使用自制工具更具防御性。

關於使用system(3)我當前使用的方法的唯一批評是,由於它在PATH查找了shred程序,因此原則上有人可能會玩這個程序並惡作劇。 但這很容易解決:使用fork(2)execve(2)使用其完整路徑調用特定的二進制文件。

就是說,如果這只是整理工作的一個低影響因素,那么簡單地mmap文件並快速將零寫入其中可能會更加直接。

您可以使用以下代碼:

#include <sys/stat.h>
#include <fcntl.h>
#include <errno.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <stdio.h>

#define BUF_SIZE 4096
#define ABS_FILE_PATH "/tmp/aaa"

int main()
{
    //get file size
    struct stat stat_buf;
    if (stat(ABS_FILE_PATH, &stat_buf) == -1)
        return errno;
    off_t fsize = stat_buf.st_size;

    //get file for writing
    int fd = open(ABS_FILE_PATH, O_WRONLY);
    if (fd == -1)
        return errno;

    //fill file with 0s
    void *buf = malloc(BUF_SIZE);
    memset(buf, 0, BUF_SIZE);
    ssize_t ret = 0;
    off_t shift = 0;
    while((ret = write(fd, buf,
                       ((fsize - shift >BUF_SIZE)?
                       BUF_SIZE:(fsize - shift)))) > 0)
        shift += ret;
    close(fd);
    free(buf);
    if (ret == -1)
        return errno;

    //remove file
    if (remove(ABS_FILE_PATH) == -1)
        return errno;

    return 0;
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM