Dan*_*Dan -1 c io low-level-io
我一直在我的桌子上敲我的头几个小时,试图弄清楚为什么下面的代码停滞不前while(chars = read(fd, buff, BUFF_SZ)) > 0).在printf上线直接以下不会被调用和一个正上方是.文件描述符返回0,是一个有效值.
char *infile = argv[1];
int fd,chars;
if ((fd = open(infile, O_RDONLY) < 0)) {
perror("open()");
exit(1);
}
printf("%s - opened (fp: %d)\n", infile, fd);
while((chars = read(fd, buff, BUFF_SZ)) > 0){
printf("%d\n", chars);
for(i = 0; i < chars; i++){
c = buff[i];
total++;
count[c]++;
}
}
Run Code Online (Sandbox Code Playgroud)
我甚至不知道如何调试这个,因为在该行之后没有触发任何内容,并且在此行之前一切正常.
完整的,可编辑的代码:
#include <string.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <stdio.h>
#include <unistd.h>
#define BUFF_SZ 4096
int main(int argc, char *argv[])
{
if(argc != 2)
perror("Wrong number of arguments!");
int fd;
char *infile = argv[1];
char buff[BUFF_SZ];
int chars,c,c2,i;
long long total = 0;
long long count[256];
char line[71];
printf("zeroing count[]\n");
for (c = 0; c < 256; c++) {
count[c] = 0;
}
if ((fd = open(infile, O_RDONLY) < 0)) {
perror("open()");
exit(1);
}
printf("%s - opened (fp: %d)\n", infile, fd);
while((chars = read(fd, buff, BUFF_SZ)) > 0){
printf("%d\n", chars);
for(i = 0; i < chars; i++){
c = buff[i];
total++;
count[c]++;
}
}
close(fd);
printf("%s closed\n", infile);
if(chars < 0){
perror("read()");
}
printf("outputting results\n");
for (c = 0;c < 256; c++) {
printf("\t%d of 256\n", c+1);
snprintf(line, 70, "%.70lf\n",
((float)count[c] / (float)total));
for (c2 = 68; c2; c2--) {
if (line[c2] != '0'
&& line[c2] != '.')
break;
}
line[++c2] = 0;
printf("%s\n", line);
}
return 0;
}
Run Code Online (Sandbox Code Playgroud)
问题是你的任务fd.
if ((fd = open(infile, O_RDONLY) < 0)) {
Run Code Online (Sandbox Code Playgroud)
应该:
if ((fd = open(infile, O_RDONLY)) < 0) {
Run Code Online (Sandbox Code Playgroud)
线索是当你说那fd是0.这是不可能的,因为fd 0是stdin,除非你在打开infile之前关闭stdin,否则不会发生这种情况.
您正在分配fd将返回值open与0 进行比较的结果,而不是分配返回值本身.