【问题标题】:write a file and make it read only写一个文件并使其只读
【发布时间】:2015-07-09 15:36:44
【问题描述】:

我在 Linux 下用 C 语言为学生写了一个数据库。因此,在输入我的数据并关闭程序后,数据将自动保存在文本文件中。我怎样才能使这个文件只读?稍后我将添加一个从文件中读取数据的函数,因此只有程序可以处理数据。任何打开文件的用户只能读取数据,但无权更改文件中的数据。换句话说,我怎样才能使我保存的数据安全? 这是一些代码:

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);
}

我写了一个例子。代码如下:

#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");
       }
   }

但我希望只有程序具有 rw 权限。其余的必须只有读取权限,包括我作为终端用户。怎么办? 我想,我会尝试阅读有关 Setuid 并使用它的信息

【问题讨论】:

  • 程序应该使用有效的 UID 运行,该 UID 被赋予对文件的写访问权限。见setuid
  • 您使用的是哪个操作系统?
  • 只要您在 Linux 上并且您的学生也在 Linux 上,您就可以在命令行中对创建的文件使用 chmod。如果您想或需要在C 代码中执行此操作,您也可以通过包含#include &lt;sys/stat.h&gt; 来使用chmod()。请参阅man 2 chmod。原型是int chmod(const char *pathname, mode_t mode);
  • @donjuedo 问题中指定了操作系统。
  • 是的,我回去读得太快了。

标签: c linux file-io


【解决方案1】:

在C语言中使用chmod改变文件的模式。

#include <sys/stat.h>

int chmod(const char *path, mode_t mode);

以下示例设置所有者、组和其他人的读取权限。

#include <sys/stat.h>

const char *path;
...
chmod(path, S_IRUSR|S_IRGRP|S_IROTH);

如果要读取权限,请使用 stat。

#include <sys/stat.h>

int stat(const char * restrict path, struct stat * restrict buf);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-10-05
    • 2021-01-23
    • 1970-01-01
    • 2015-12-29
    • 1970-01-01
    相关资源
    最近更新 更多