c - Linux C,文件验证不起作用

标签 c linux validation

我想用 C 编写一个简单的文件验证函数,以在读取文件之前验证文件是否存在。出于某种原因,我的验证代码一直为有效文件返回 false。该文件与编译后的程序位于同一位置。我尝试使用完整路径,并且只使用文件路径。为什么我的函数找不到文件?

#include <stdio.h>
#include <stdlib.h>
#include <sys/stat.h>
#include <stdbool.h>
// #include <linux/string.h>
const char* CONFIG_FILE =  "/home/matt/atc_config"; //"/config.ini";

bool path_status (char *s_path);

//bool Validate_File(const char* path);
//bool Read_Config_File(const char* path, char* contents);
//bool Parse_Config_Data(const char* data, MeterParams* mp);

int main(int argc, char** argv)
{
    // Get path to config file. This assumes our config file
    // is kept in the same folder as this execuable file.

    char file[256];
    strcpy (file, argv[0]);
    strcat (file, CONFIG_FILE);

    puts ( file );

// Validate config file is present and we
// can access it.
if ( path_status ( CONFIG_FILE )) // ( file ))
{
    puts ("file ok.");
    // Read the file's contents.

}
else
{
    puts ("file not ok.");
}

return (EXIT_SUCCESS);
}

bool path_status (char *s_path)
{
   /* The following mask values are defined for the file type of the
   st_mode field:
   * 
       S_IFMT     0170000   bit mask for the file type bit field

       S_IFSOCK   0140000   socket
       S_IFLNK    0120000   symbolic link
       S_IFREG    0100000   regular file
       S_IFBLK    0060000   block device
       S_IFDIR    0040000   directory
       S_IFCHR    0020000   character device
       S_IFIFO    0010000   FIFO
* ref: http://man7.org/linux/man-pages/man2/stat.2.html
*/ 

// 'stat'returns information about file, folder, link or socket.
// It fills a structure, also named 'stat'.
// On success, zero is returned. On error, -1 is returned, and
// errno is set appropriately.

struct stat st;
bool ret = false;    
if (stat(s_path , &st) == 0) // // Zero indicates path status successfully obtained.
{
    ret = (st.st_mode & S_IFMT == S_IFREG); 
}    
    return ret;
}

谢谢,
马特

最佳答案

这里有一个优先级错误:

ret = (st.st_mode & S_IFMT == S_IFREG);

这解析为

ret = (st.st_mode & (S_IFMT == S_IFREG));

因为 ==& 绑定(bind)得更紧(出于愚蠢的原因)。 S_IFMT == S_IFREG0anything & 00,所以 ret始终为 0


修复:

ret = (st.st_mode & S_IFMT) == S_IFREG;

关于c - Linux C,文件验证不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38902455/

相关文章:

c - 为什么在printf中指定为整数的char被正确打印

c - 使用枚举数组和 typedef 数组编译 C 代码时出错

php - 当我尝试为设施 LOG_LOCAL1 配置日志时出现 syslog-ng 错误

linux - 如何在 Linux 中的另一个进程终止时得到通知

c - 确定 C 字符串是否是 C 中的有效 int

python - 任意长度子串的游程长度编码

c - 阻塞的系统调用不会让 SIGKILL 终止进程

Javax 验证 : Constraint Violations for Map

laravel - 如果没有值或 null laravel,请不要更改值

C - undefined reference - 除了使用 -lm 进行编译之外,还有其他选择吗?