2015-02-07 82 views
0

我正在尝试从文件中读取字符并使用系统调用来计算文件中某个特定字的频率,但我的read()调用之一的行为令我困惑。这是我写的代码:`在C中读取()`系统调用不会读取字节

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

+1

read函数返回什么?如果它为零,则表示“文件”已关闭,如果为负,则表示错误,您需要检查错误“errno”。 – 2015-02-07 20:29:20

+1

另外,*你怎么知道'read'调用不起作用?这是因为字符串比较失败,你可能想看看'lowerCase'而不是?可以在调试器中运行并逐行浏览代码,同时观察所有变量的值和内容,或者直接在'read'后面输出字符串(如果'read'返回一个正数)。 – 2015-02-07 20:31:01

+0

该调用返回0,但在读取50个字符文件的三个字符后发生。据我所知,文件没有关闭,文件末尾也没有文件指针。我也在'gdb'中完成了它,并且所有在缓冲区中的都是'\ 001' – rafafan2010 2015-02-07 20:32:39

回答

1

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

所以修正路线是:seekError = lseek(fd,(off_t)-1,SEEK_CUR);

1

它不应该是必要的投-1off_t类型。它看起来像你真正的错误是,你没有包括<unistd.h>,所以lseek没有正确地声明,当你使用它。无论是该系统的执行lseek还是存在严重错误。