0
点赞
收藏
分享

微信扫一扫

C代码规范:使用文件路径前必须进行规范化并校验,fwrite写入文件前,要设置文件权限

使用文件路径前必须进行规范化并校验

文件路径来自外部数据时,必须对其做合法性校验,如果不校验,可能造成系统文件的被任意访问。 但是禁止直接对其进行校验,正确做法是在校验之前必须对其进行路径规范化处理。这是因为同一个文 件可以通过多种形式的路径来描述和引用,例如既可以是绝对路径,也可以是相对路径;而且路径名、 目录名和文件名可能包含使校验变得困难和不准确的字符(如:“.”、“..”)。

所以下面才是正确的示例:

#include <stdlib.h>
#include <stdio.h>
#include <limits.h>

int main() {
    const char *relative_path = "./test.txt";
    char absolute_path[PATH_MAX];

    if (realpath(relative_path, absolute_path) == NULL) {  // 先用这个
        perror("Error resolving absolute path");
        return EXIT_FAILURE;
    }

    FILE *file = fopen(absolute_path, "r");
    if (file == NULL) {
        perror("Error opening file");
        return EXIT_FAILURE;
    }

    // Use the file...

    fclose(file);

    return EXIT_SUCCESS;
}

  

否则会有:In fopen: It should canonical file path before use it, path arg is filename

 

此外,fwrite写入文件前(第一次),要设置文件权限:should set permission of file handle "file" before use it

 

如下是正确的代码 示例:

 

#include <fcntl.h>
#include <unistd.h>
#include <stdio.h>

int fd = open(filename, O_WRONLY | O_CREAT, S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH); // 创建文件权限
if (fd == -1) {
    // Handle error
}

FILE *file = fdopen(fd, "wb"); // 然后再打开写入
if (file == NULL) {
    // Handle error
}

// Use fwrite with the FILE *
size_t result = fwrite(data, sizeof(data[0]), count, file);
if (result != count) {
    // Handle error
}

fclose(file);

  



举报

相关推荐

0 条评论