- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
所以我想测试给定的文件是否正常。
#include <stdio.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
#include <string.h>
#include <errno.h>
int main(int argc, char **argv)
{
// Input check.
if (argc != 2) {
fprintf(stdout,"Format: %s <filename.txt>\n", argv[0]);
return -1;
}
// Make sure the file is a regular file.
int fd;
if ((fd = open(argv[1], O_RDONLY) == -1)) {
fprintf(stdout, "%s", strerror(errno));
return -1;
}
struct stat st;
if ((fstat(fd, &st) == -1)) {
fprintf(stdout, "%s\n", strerror(errno));
return -1;
}
if (!(S_ISREG(st.st_mode))) {
fprintf(stdout, "Error, invalid file\n");
return -1;
}
close(fd);
return 0;
}
我运行:.\a in.txt
我不知道到底发生了什么,但是当我尝试测试文件是否正常时(最后一个 if 语句),它失败了。我测试了 fstat 是否失败,但它没有。
最佳答案
问题是:
if ((fd = open(argv[1], O_RDONLY) == -1)) {
相等运算符 ==
的优先级高于赋值运算符 =
。所以上面的解析为:
if (fd = (open(argv[1], O_RDONLY) == -1)) {
将比较结果赋值给 fd
,结果为 0 或 1。这些值恰好都是 stdin 和 stdout 的有效打开文件描述符,因此 fstat
调用成功并让您了解这些流之一的状态。
您需要先调整括号以进行分配:
if ((fd = open(argv[1], O_RDONLY)) == -1) {
此外,看起来您还有其他 if
语句,这些语句具有一组您可以删除的冗余括号。你想避免这种情况,因为那些额外的括号可以消除关于你所做的事情的警告。
关于c - S_ISREG 返回 0,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66284985/
我在仅计算目录中的常规文件时遇到了一些问题。 这是我的代码: int show_regular_files(char ** path) { DIR * dp = opendir(*path);
问题 posix 宏 S_ISREG、S_ISDIR 等仅限于 linux 吗?我需要找出答案,因为我正在尝试编译 CURL它正在尝试在 Windows 上使用它们 我可以使用什么包含文件在 Wind
所以我想测试给定的文件是否正常。 #include #include #include #include #include #include int main(int argc, char
所以我想测试给定的文件是否正常。 #include #include #include #include #include #include int main(int argc, char
我在检索文件属性的 C 程序中遇到宏 S_ISREG()。不幸的是,网上没有关于这个宏的任何基本信息。关于它有一些更高级的讨论,但它们超出了我正在寻找的范围。 什么是 S_ISREG(),它有什么作用
我需要使用 C 在 linux 中制作一个应用程序,我需要输入一个文件夹路径并将所有文件和子目录复制到一个新文件夹中。问题是当我尝试检查路径是文件夹还是文件时,程序总是采用文件夹的路径,即使它是文件。
我正在尝试获取路径中的项目列表并确定它是文件还是文件夹。 我正在 Windows 中运行该脚本。 sftp = sftp_connection(host, username, password, IN
为什么我的 S_ISDIR 和 S_ISREG 不能返回正确的目录/文件名? 当我使用我用 3 个其他目录和一个文本文件创建的测试目录运行程序时,只有 Dir 的 printf() 执行。 #incl
这是我编写的一个 C 程序,用于递归导航和输出目录和常规文件。它在我的 Linux 机器上编译和运行良好。但是在 Solaris 上,dit->d_type == 8 检查和其他类似的检查不起作用,因
让我们考虑以下 3 行代码: struct stat buffer; status = lstat(file.c_str(), &buffer); bool Flag = S_ISREG
从中获取的代码可以正常编译。它打印目录中的文件名,前面有一个字母选项:d、f、l 或 o 取决于他们的文件类型(o 为其他)。但是,我在目录 /etc/network 上测试了它,该目录有一个名为 r
我是一名优秀的程序员,十分优秀!