簡體   English   中英

當我嘗試從txt文件讀取時,它返回:無法讀取輸入文件

[英]when I try to read from txt file it returns : Cannot read input file

我正在嘗試編寫一個比較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;
}

讓自己變得更美好,向系統詢問errno ,並閱讀有關系統的手冊,調用read(2),open(2),...和errno(3)

(讀取(2)例如是手動頁面地址,他說:手冊頁“閱讀”第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

問題在這里:

您聲明:

 char *firstFile = NULL, *secondFile = NULL;

然后你用

read(fd1, firstFile, 1);

firstFileNULL ,因此read失敗。

像這樣聲明firstFilesecondFile

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

檢查文件是否存在於給定的路徑中

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM