Legend
Legend

Reputation: 116950

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?

Upvotes: 2

Views: 1575

Answers (4)

tur1ng
tur1ng

Reputation: 3309

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

Upvotes: 1

tsg
tsg

Reputation: 2041

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

Upvotes: 1

caf
caf

Reputation: 239201

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

Upvotes: 3

notacat
notacat

Reputation: 344

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!

Upvotes: 3

Related Questions