C:删除功能会删除所有文件吗?
我正在使用这样的东西:
char *file;
file = (char *)malloc(BUFSIZE * sizeof(char));
printf("Enter the filename:");
scanf("%s", file);
if(remove(file)) {
printf("Error while removing");
}
我创建了两个文件:
touch filetobedeleted1.txt
chmod 777 filetobedeleted1.txt
touch filetobedeleted2.txt
chmod 444 filetobedeleted2.txt
现在,我的程序删除了这两个文件,但这不应该发生,对吧?有人知道代码有什么问题吗?
编辑:添加了将名称放入文件的代码...
好吧...看起来这一切都取决于目录上设置的权限,但是有没有办法使用文件权限作为检查?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
在 POSIX 文件系统语义下,用于删除文件的权限检查是是否可以写入该文件所在的目录; 不您是否对文件本身具有写权限。
(如果目录设置了粘性位,那么您也必须是该文件的所有者 -
/tmp
使用此)。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).删除文件只需要对目录有写访问权限。
严格来说,您要删除的是对文件的引用,即硬链接。在该文件的所有链接都消失之前,该文件本身不会被删除。
使用 rm 命令尝试一下!
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()
调用unlink()
,并且根据man 2 unlink
,只需要对 parent 的写权限> 目录。remove()
callsunlink()
, and according toman 2 unlink
, that only needs write permissions to the parent directory.您可以使用
getumask()
函数并在调用remove()
之前对其进行检查。You can use the
getumask()
function and give it a check before callingremove()
.