Reputation: 467
I write a database for students in C under Linux. So after entering my data and after closing the program, the data will be saved automatically in a text-file. How can I make this file read only? I will later add a function that will read the data from the file, so only the program can process data. Any user who opens the file can only read data but he has no rights to change the data in the file. In other words how can I make my saved data secure? Here is some code:
void writeData(){
FILE * fpw;
fpw=fopen("database.txt","wb");
if(fpw==NULL){
printf("the file cannot be opened");
exit(1);
}
int i;
for(i=0;i<SIZE;i++){
fprintf(fpw,"%s, %s, %d, %s , %s;\n",
(db+i)->lastname,(db+i)->firstname,(db+i)->mNr, (db+i)->subject, (db+i)->nationality);
}
fclose(fpw);
}
I wrote an example. Here is the code:
#include <sys/stat.h>
#include <stdio.h>
int main(int argc, char** argv){
char mode[]="111";
int in=strtol(mode,0,8);
int ret_value=chmod("./file.csv",in);
if(ret_value!=0){
printf("failed to change mode");
}
}
But I want that only the program has the rw-rights. The rest must only have read-rights including me as a terminal-user. How can do it? I think, I will try to read about Setuid and to use it
Upvotes: 1
Views: 5469
Reputation: 12641
Use chmod
in C to change the mode of file.
#include <sys/stat.h>
int chmod(const char *path, mode_t mode);
The following example sets read permissions for the owner, group, and others.
#include <sys/stat.h>
const char *path;
...
chmod(path, S_IRUSR|S_IRGRP|S_IROTH);
If you want to read the permissions, use stat.
#include <sys/stat.h>
int stat(const char * restrict path, struct stat * restrict buf);
Upvotes: 2