如何在 C 语言中编写 root 拥有的文件?

How to write a file owned by root in C?

提问人:Maruko 提问时间:10/17/2023 最后编辑:Maruko 更新时间:10/17/2023 访问量:81

问:

我怎样才能写进root拥有的文件,例如在/etc中? 特别是,我需要让普通用户拥有可执行文件,因此我不能以 root 身份运行它,也不能使用 sudo 调用它。

我知道这不是一个特定的 C 问题,但是我想知道 C 中可能的解决方案。 另一种语言的相同解决方案也可能有所帮助。

使用 C 编程语言的示例

/*
 How can I write into a file owned by root user?

 -rwxrwxr-x  1 user user 8480 ott 17 11:48 test
 -rw-rw-r--  1 user user  432 ott 17 11:48 test.c
 -rw-rw-r--  1 root root   20 ott 17 11:48 textfile.txt

 $ ./test 
Test how to write a file owned by root
File can't be opened
Segmentation fault (core dumped)
*/

#include <stdio.h>

int main(int argc, char **argv)
{
    printf("Test how to write a file owned by root\n");

    FILE *fp;
 
    fp = fopen("textfile.txt", "w");
 
    if (fp != NULL) {
        fprintf(fp, "Wite success!\n");
        printf("\n Details successfully written to the file\n\n");
    }
    else
        printf("File can't be opened\n");
 
    fclose(fp);

    return 0;
}

谢谢

C 文件权限 fopen 用户权限

评论

1赞 pmg 10/17/2023
这不是一个 C 问题(如果你能用 Java、BASIC 或任何其他语言解决它,请将同样的解决方案应用于 C)。
0赞 Maruko 10/17/2023
我知道这不是一个特定的 C 问题,但是我想知道 C 中可能的解决方案。另一种语言的相同解决方案也可能有所帮助。
1赞 pmg 10/17/2023
不相关:有 1 个太多。由于您在(文本)模式下打开了文件,因此它将执行正确的 Windows 操作,并在看到它为您提供磁盘上的最终结果时写入。如果您使用的是 Linux,那么编写 Windows 文件是正确的......但是,您应该以二进制模式()打开该文件。fprintf(fp, "Wite success!\r\n");'\r'"w"fwrite()"\r\n""\n""...success!\r\r\n""\r\n""wb"
0赞 Gerhardh 10/17/2023
这根本不是编程问题。您需要为可执行文件设置权限,无论您使用哪种语言创建可执行文件。这只是一个 Linux 问题。可能更适合超级用户堆栈
2赞 n. m. could be an AI 10/17/2023
你怎么能打破规则并逍遥法外?你不能。

答: 暂无答案