How to remove (completely deleting) a file using C

2019-01-25 16:56发布

I've been curious how rem in Linux works and trying to write my own C code that can delete a file but when I searched for the answer, I only got the programs that were using remove() system call.

Is there any other way of doing it without using system call like writing your own code to do the job?

I've accomplished copying file through C filing but can't find a solution to delete a file through C.

5条回答
三岁会撩人
2楼-- · 2019-01-25 17:42

If you don't want to use the clean, usual way, you can open /dev/sd** and play with your file system.

Btw, remove() isn't a syscall (man 3 remove).

查看更多
疯言疯语
3楼-- · 2019-01-25 17:42

The traditional way to delete a file is to use the unlink(2) function, which is called from remove(3), if path is a file.

查看更多
聊天终结者
4楼-- · 2019-01-25 17:46

If you want to delete a file use the

remove

function. If you want to have a look behind the scenes of the standard library, you may download the source of the glibc (e.g.) and have a look at the implementation. You will see that actually a INTERNAL_SYSCALL will be performed on linux os:

result = INTERNAL_SYSCALL (unlink, err, 1, file);

(from /sysdeps/unix/sysv/linux/unlinkat.c from the debian eglibc-2.15 package)

If you want to go further and even not use that syscall you will have to implement your own file system logic since the file system syscall just gives an abstraction layer to different filesystems.

查看更多
别忘想泡老子
5楼-- · 2019-01-25 17:52
#include<stdio.h>
#include<stdlib.h>
#include<unistd.h>
#include <sys/types.h>
#include <sys/wait.h>


int main(){
        int status;
        pid_t pid = fork();
        if(-1 == pid){
                printf("fork() failed");
                exit(EXIT_FAILURE);
        }else if(pid == 0){
                execl("/bin/sh", "sh", "-c", "rm /tmp/san.txt", (char *) NULL);
        }else{
                printf("[%d]fork with id %d\n",pid);
                waitpid(pid,&status,0);
        }
return 0;
}
查看更多
时光不老,我们不散
6楼-- · 2019-01-25 17:57
int unlink (const char *filename)

The unlink function deletes the file name filename. The function unlink is declared in the header file unistd.h. This function returns 0 on successful completion, and -1 on error

查看更多
登录 后发表回答