当我尝试从txt文件中读取它时返回:无法读取输入文件

时间:2016-03-30 08:53:17

标签: c linux gcc

我正在尝试编写一个比较2个文件的程序,如果它们相等则返回。

我只能使用函数: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;
}

3 个答案:

答案 0 :(得分:2)

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

的手册

(例如,阅读(2)是一个手册页地址,说:手册页&#34;阅读&#34;在第2部分,阅读man man部分。)

#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

答案 1 :(得分:1)

问题在于:

你声明:

 char *firstFile = NULL, *secondFile = NULL;

然后你使用

read(fd1, firstFile, 1);

firstFileNULL时,因此read失败。

像这样声明firstFilesecondFile

char firstFile[1];
char secondFile[1];

答案 2 :(得分:-1)

检查文件是否存在于给定路径中

相关问题