Wednesday, February 7, 2024

[SOLVED] C: The remove function removes all files?

Issue

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?


Solution

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).



Answered By - caf
Answer Checked By - Cary Denson (WPSolving Admin)