Search code examples
clinuxrm

cannot delete (rm) a file in c program but can in shell


My C program (on Linux) needs to delete a file, say, /home/me/myfile, here is how I do it in my program

...
system ("rm -f /home/me/myfile");
...

When running this program, I got a message saying permission denied. BTW, ls -al /home/me/myfile returns -rw-r--r--

However, under the same user account and in the same shell I execute the C program, I can simple delete the file by typing rm -f /home/me/myfile

What did I miss here?

Thanks,

Update: Using remove(/home/me/myfile) or unlink(/home/me/myfile), the file can be deleted in my program.


Solution

  • For a start, it's the permissions on the directory that control whether you can delete a file.

    But, having said that, there are numerous things that could be different between the two situations. Your program might be running as a different user (such as with the SETUID bit), the path may be different, leading to a different rm being run, the program may set up a chroot jail so that it can no longer even see the file (though that may manifest as a different error), and so forth. The possibilities are rather large.

    However, C provides a call to delete files, called unlink - you should use that in preference and then check errno.

    I would suggest checking the output of which rm in both cases, along with the full details of the file and executable, owner and permissions.