使用低级函数清除文件内容

发布于 2025-01-19 09:10:54 字数 918 浏览 3 评论 0原文

我想编写一个能够删除文件内容的函数。

我对如何执行此操作有一些想法,这是从它们中提出的程序:

/*fclr - clear file contents*/
#include <fcntl.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>

int main(int argc, char* argv[]){
    int fd;

    if(--argc == 0)
        fprintf(stderr, "Incorrect syntax. Usage: cat <filename1> <filname2> ... <filenameN>.\n");
    while(--argc > 0){
        char c = EOF;
        if((fd = open(*++argv, O_WRONLY, 0)) == -1)
            fprintf(stderr, "Unable to open the file.\n");
        lseek(fd, 0, SEEK_SET); //lseek here is redundant.
        write(fd, &c, sizeof(char));
        close(fd);
    }
} 

基本上,我认为,如果看到一个很大的字符,就必须拥有并结束内存。因此,除了\ 0适用于刺,我认为EOF将为实际文件做,但行不通。文件运行后,内容仍在那里。

您是否有任何建议来解决此问题。

(我确实知道在“ W”模式上打开Fopen的文件将删除整个内容,但我想通过低级功能实现相同的结果)

I would like to write a function able to delete contents of files.

I have some thoughts of how to do it and here is the program that come up from them:

/*fclr - clear file contents*/
#include <fcntl.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>

int main(int argc, char* argv[]){
    int fd;

    if(--argc == 0)
        fprintf(stderr, "Incorrect syntax. Usage: cat <filename1> <filname2> ... <filenameN>.\n");
    while(--argc > 0){
        char c = EOF;
        if((fd = open(*++argv, O_WRONLY, 0)) == -1)
            fprintf(stderr, "Unable to open the file.\n");
        lseek(fd, 0, SEEK_SET); //lseek here is redundant.
        write(fd, &c, sizeof(char));
        close(fd);
    }
} 

Basically, I suppused, if a file is seen a very big array of characters, is has to have and end in memory. So as well as \0 works for stings, I thought EOF will do for actual files, but is not working. After the file is ran, the content is still there.

Do you have any suggestion to solve this problem.

(I do know that opening a file with fopen on "w" mode will delete the whole content, but I would like to achieve the same result with low level functions)

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

终难遇 2025-01-26 09:10:54

您为什么不只是尝试按照以下方式打开?它按照您的期望将文件截断。

open(*++argv, O_TRUNC | O_WRONLY);

Why don't you only try to open as following? It truncates the file as you expect.

open(*++argv, O_TRUNC | O_WRONLY);
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文