-1

几个小时以来,我一直把头撞在桌子上,试图弄清楚为什么下面的代码在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]++;
    }
}

我什至不知道如何调试它,因为在相关行之后没有触发任何内容,并且在此行之前一切看起来都很好。

完整的可编译代码:

#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;
}
4

2 回答 2

6

问题是您分配给fd.

if ((fd = open(infile, O_RDONLY) < 0)) {

应该:

if ((fd = open(infile, O_RDONLY)) < 0) {

线索是当您说它fd是 0 时。这不太可能,因为 fd 0 是标准输入,除非您在打开 infile 之前关闭标准输入,否则这种情况不会发生。

You were assigning fd the result of comparing the return value of open with 0, instead of assigning the return value itself.

于 2012-09-10T02:02:41.027 回答
1

You only need to rearrange the parenthesis

if ((fd = open(argv[1], O_RDONLY)) < 0) {
于 2012-09-10T02:02:59.437 回答