`read()`C中的系统调用不读取字节

时间:2015-02-07 20:26:05

标签: c system-calls

我试图从文件中读取字符并使用系统调用计算文件中特定单词的频率,但我read()个调用之一的行为让我感到困惑。这是我写的代码:

int counter, seekError,readVal;
counter = 0;

char c[1];
char *string = "word";

readVal = read(fd,c,1);
while (readVal != 0){ // While not the end of the file
    if(c[0] == string[0]) { // Match the first character
                seekError = lseek(fd,-1,SEEK_CUR); // After we find a matching character, rewind to capture the entire word
                char buffer[strlen(string)+1];
                buffer[strlen(string)] = '\0';
                readVal = read(fd,buffer,strlen(string)); // This read() does not put anything into the buffer

                if(strcmp(lowerCase(buffer),string) == 0)
                        counter++;

                lseek(fd,-(strlen(string)-1),SEEK_CUR); // go back to the next character
        }
        readVal = read(fd,c,1);
}

在我使用的所有读取调用中,我能够从文件中读取没有问题的字符。但是,无论我如何尝试阅读字符,readVal = read(fd,buffer,strlen9string));行都不会将任何内容放入buffer。幕后是否有任何可以解释这种行为的事情?我也尝试在不同的计算机上运行此代码,但我仍然在buffer处没有得到任何内容。

2 个答案:

答案 0 :(得分:2)

没有必要将-1转换为off_t类型。看起来您真正的错误是您没有包含<unistd.h>,因此在您使用lseek时未正确声明lseek。您的系统{{1}}的实现中存在严重错误。

答案 1 :(得分:1)

此处的问题是-1行中的seekError = lseek(fd,-1,SEEK_CUR);被解释为4294967295。将其转换为off_t类型后,系统会将偏移量解释为-1而不是大数字。

因此更正的行是:seekError = lseek(fd,(off_t)-1,SEEK_CUR);