gpt4 book ai didi

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

转载 作者:塔克拉玛干 更新时间:2023-11-02 23:22:29 25 4
gpt4 key购买 nike

我想用 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com