c - 当我尝试读取 txt 文件时,它返回 : Cannot read input file

标签 c linux gcc

我正在尝试编写一个程序来比较两个文件并返回它们是否相等。

我只能使用以下函数:fork、dup、dup2、open、write、exec、read。

当我在linux gcc上编译程序时,它返回 无法读取输入文件

shay@shay-Latitude-E6410 ~/workspace/targ1OS $ ./comp.out input.txt input.txt Cannot read input file

代码:

/*
* This function checks if the files are similar or similar by case    sensitive
 * it gets 2 files, and returns: 3 if identical, 2 if identical but only if not
 * case sensitive or 1 else.
 */
int CheckSimilar(char *path1, char *path2){

//open the files
int fd1 = open(path1, O_RDONLY), fd2 = open(path2, O_RDONLY);
int flag = 1;//this flag is to check for case sensitive
char *firstFile = NULL, *secondFile = NULL;
int readBytes, read2ndFile;

if (fd1 == -1 || fd2 == -1){
    write(2, "Cannot open input file\n", 24);
    return -1;//checks if there is a problem opening the file
}

while (1){

    readBytes = read(fd1, firstFile, 1);
    read2ndFile = read(fd2, secondFile, 1);

    if (readBytes < 0 || read2ndFile < 0){
        write(2, "Cannot read input file\n", 24);
        return -1;
    }//checks if there is a problem reading chars from the file

    if (!readBytes || !read2ndFile)
        break;

    if (*firstFile == *secondFile)
        continue;//the chars are equal
    //checks if it's an abc char
    else if ((*firstFile > 64 && *firstFile < 91) ||
            (*firstFile > 96 && *firstFile < 123)){
        // checks for not case sensitive
        if ((*firstFile - *secondFile) == 22 ||
                (*firstFile - *secondFile) == -22)
            flag = 0;
    }
    else
        return 1;
}

close(fd1);
close(fd2);

if (readBytes != read2ndFile)
    return 1;
if (flag)
    return 2;
return 3;
}

最佳答案

让自己的世界变得更美好,向系统询问errno,并阅读有关系统调用 read(2)、open(2)、... 和 errno(3) 的手册

(例如read(2)是一个手册页地址,表示:手册页“read”第2节,阅读man man about各部分)。

#include <stdio.h>
#include <string.h>
#include <errno.h>
[...]

    char* err = strerror(errno);
    char* errlen = err ? strlen(err): 0;
    char* form = "Cannot read input file since \"%s\".\n"
    if (errlen == 0) {
        form = "Cannot read input file failed with unknown error %d.\n";
        fprintf(stderr, form, errno);
    }
    else {
        fprintf(stderr, form, err);
    }

由于您无法使用 fprintf,因此我将其留给您来编写表格。至少你应该在读取失败后打印出errno

关于c - 当我尝试读取 txt 文件时,它返回 : Cannot read input file,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36304001/

相关文章:

关于系统托盘最小化 - WIN API 的几个问题

c - CPU 上的乘加 `a = a*2 + b` 指令?

c - 这是与按钮/操纵杆交互的正确方式吗?

c - 内核中是否有与 perror 等效的东西?

linux - 将 .gz 文件拆分为多个 1GB 压缩 (.gz) 文件

linux - crontab - 这些命令每 x 分钟运行一次的区别

linux - Java 类路径中 '*' 的特殊含义是什么?

c++ - 外部打印函数如何编译

macos - 错误 : command 'gcc' failed with exit status 1 -Python3. 7 MacOS Catalina

c - 如何将 -libm 传递给 MPICC? libimf.so : warning: feupdateenv is not implemented and will always fail