2012-09-10 21 views
-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; 
} 
+1

如果在程序挂起时,你向它输入了几句话,会发生什么,然后按回车键,然后控制d,然后再回来吗?另外,请发布一个可编译和运行的完整程序。 – zwol

+0

它做它应该做的事情与infile。这是有道理的......“标准输入”为零。它应该是从命令行上的infile中读取的,尽管...我现在会发布完整的代码。 – Dan

+0

从标题中可以看出,它是从终端(或者其他设备或管道)读取的。 –

回答

6

的问题是你分配给fd

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

应该是:

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

当你说fd为0,即是不可能的,因为FD 0是标准输入,而这不应该发生,除非你打开前关闭标准输入的线索是INFILE。

您将fd的结果赋值为open的返回值与0进行比较,而不是分配返回值本身。

+0

呃!我不能相信我错过了这一点。让我疯了。谢谢! – Dan

+0

不要打垮自己。你甚至不接近第一个,也不会是最后一个;它在使用=时,当你的意思是==,我在过去一周左右完成了自己的工作。但是在发布之前你是否尝试过使用它? – Barmar

+1

这是今天发布到[c]的此错误的第三个变体。人们应该使用好的编译器和适当的警告级别。他们还应该阅读他们编写的代码......何时((表达式))有必要? –

1

你只需要重新排列括号

if ((fd = open(argv[1], O_RDONLY)) < 0) {