无法执行 if 处的命令

标签 c

我的程序有问题。当我调试它时 fd2 is < 0并没有得到那个如果。检查一下。

printf("Enter file name: ");
scanf(" %s", file_name);

 printf("Enter file name2: ");
 scanf(" %s", file_name2);

fd=open(file_name, O_RDWR, S_IRWXU);
fd2=open(file_name2, O_RDWR, S_IRWXU);

if(fd2<0){
    printf("Error opening file!\n%s\n", strerror(errno));
    return(-1);
}

if(fd<0){
    printf("Error opening file!\n%s\n", strerror(errno));
    return(-1);
}

enter image description here

最佳答案

效果很好。检查open()的返回值是否正确,如果open()失败则说明权限问题。

fd=open(file_name, O_RDWR, S_IRWXU);

fd 是一个文件描述符,您可以使用

来检查它
ls -l /proc/pid/fd
ls -l /proc/pid/fd   /* check here what value its prints */

还有

#include<errno.h>
int main() {

            char file_name[50],file_name2[50];
            printf("Enter file name: ");
            scanf(" %s", file_name);
            int fd,fd2;
            printf("Enter file name2: ");
            scanf(" %s", file_name2);

            fd=open(file_name, O_RDWR, S_IRWXU);
            if(fd < 0) {
                    printf("Error opening file!\n%d\n", strerror(errno));/* use  %d instead of %s */
                    return 0; /* upon failure open() returns 0 not -1 */
            }
            fd2=open(file_name2, O_RDWR, S_IRWXU);
            if(fd2 < 0) {
                    printf("Error opening file!\n%d\n", strerror(errno));
                    return 0;
            }
    }

关于无法执行 if 处的命令,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48965239/

相关文章:

iphone - Objective-c -> 结构运算符

c - 如何创建分布式阵列 MPI

c - 如何更改窗口的 X 和 Y 坐标而不重新创建它

objective-c - Clang 静态分析器警告 "Null pointer argument in call to CFRelease"

C 字符串比较不允许空格键

c++ - 为什么包括与RTCZero库不兼容?

c - GCC 内联汇编没有将数据复制到输入寄存器

c可变参数函数,相同的参数,不同的格式

c - 手册 "encryption"只输出0到文件

c - 使用表查找的 Alpha 混合没有预期的那么快