开发者

C: The remove function removes all files?

I am using something like this:

char *file;
file = (char *)malloc(BUFSIZE * sizeof(char));
printf("Enter the filename:");
scanf("%s", file);
if(remove(file)) {
   printf("Error while removing");
}

I created two files:

touch filetobedeleted1.txt
chmod 777 filetobedeleted1.txt

touch filetobedeleted2.txt
chmod 444 filetobedeleted2.txt

Now, my program removes both the files but that is not supposed to happen right? Anyone knows开发者_如何学编程 what is wrong with the code?

EDIT: Added the code for putting the name into file...

Ok... looks like it all depends on the permissions set on the directory but then is there a way to use file permissions as a check?


Under POSIX filesystem semantics, the permission check used for deleting a file is whether you can write to the directory that the file is in; not whether you have write permission on the file itself.

(If the directory has the sticky bit set, then you must also be the owner of the file - /tmp uses this).


Removing a file only needs write access on the directory.

Strictly speaking, what you're removing is a reference to the file, a hardlink. The file itself will not be deleted until all links to the file are gone.

Try it with the rm command!


remove() calls unlink(), and according to man 2 unlink, that only needs write permissions to the parent directory.


You can use the getumask() function and give it a check before calling remove().

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜