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