Is it possible to protect a file in c?
I have written a password program in c. and I saved the password in a text file using some encryptiion and retrieving the old password from a file using decryption techniques So that user cannot see the password.Yes ofcourse this might not be the efficient way to do because there is a chance for user to delete the text file.
But still I want to lock (protect) a file using my c password code.I have searched on google I found perl can be used to lock a file.The question is that possible in c? Do we have any function like flock in perl? or suggest me some functions that can be helpful to develop a file lock function in c.becuase People may say we have c# and lots of stuff out to lock a file and wh开发者_StackOverflow社区y your sticking to c? but I like challenging the things.So please let me know If theres something I need to learn.Thank you in advance.
You can, on a POSIX system, use fcntl()
along with the F_SETLK
value for the command argument, and then set F_WRLCK
(i.e, and exclusive lock) in the struct flock
data-member l_type
.
So for instance (add your own error-detection mechanisms):
#include <fcntl.h>
#include <unistd.h>
struct flock fl;
int file_descriptor;
int file_length;
fd = open("my_password_file", O_RDWR);
//... get the length of the file and set the variable file_length
fl.l_type = F_WRLCK;
fl.l_whence = SEEK_SET;
fl.l_start = 0;
fl.l_len = file_length;
//set the exclusive-lock on the file
fcntl(fd, F_SETLK, &fl);
http://linux.die.net/man/2/flock
What do you want to achieve with flock
? flock
or any other kind of file locking will not prevent the user from deleting the file. He may not be able to do it while your program is running, but once your program terminates, all locks are freed.
flock is used to gain some kind of exclusiveness for accessing a file during some kind of I/O operation.
hth
Mario
On Windows I could use Process Explorer or Handle to close the handle out from under your program. So even if you could do it, someone else could undo it.
精彩评论