我正在尝试从文件中读取字符并使用系统调用来计算文件中某个特定字的频率,但我的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
。
read函数返回什么?如果它为零,则表示“文件”已关闭,如果为负,则表示错误,您需要检查错误“errno”。 – 2015-02-07 20:29:20
另外,*你怎么知道'read'调用不起作用?这是因为字符串比较失败,你可能想看看'lowerCase'而不是?可以在调试器中运行并逐行浏览代码,同时观察所有变量的值和内容,或者直接在'read'后面输出字符串(如果'read'返回一个正数)。 – 2015-02-07 20:31:01
该调用返回0,但在读取50个字符文件的三个字符后发生。据我所知,文件没有关闭,文件末尾也没有文件指针。我也在'gdb'中完成了它,并且所有在缓冲区中的都是'\ 001' – rafafan2010 2015-02-07 20:32:39