我有以下代码
int * counter(const char *filename, bool bytes_flag, bool words_flag, bool lines_flag){
int * counts = malloc(sizeof(int) * 3);
int line_count = 0;
int word_count = 0;
int byte_count = 0;
size_t line_size = LINE_MAX;
FILE * file_stream;
char * line_buffer;
printf("%d %d %d\n", line_count, word_count, byte_count);
file_stream = fopen(filename, "r");
if (file_stream == NULL) {
printf("File count not be opened.\n");
}
else{
line_buffer = (char *)malloc(line_size);
while (getline(&line_buffer, &line_size, file_stream) != EOF){
if (lines_flag){line_count++;}
for ( int i = -1; line_buffer[i] != '\n'; i++){
byte_count++;
if (isspace(line_buffer[i]) && !isspace(line_buffer[i-1])){
word_count++;
}
}
//byte_count++;//Count last \n character
}
fclose(file_stream);
printf("\n");
printf("%d\n", line_count);
printf("%d\n", word_count);
printf("%d\n", byte_count);
printf("\n");
counts[0] = line_count;
counts[1] = word_count;
counts[2] = byte_count;
}
return counts;
}
我正在输入以下文件
The Project Gutenberg eBook of The Art of War
This ebook is for the use of anyone anywhere in the United States and
我的输出几乎就是我想要的,但字数1太高了.发生这种情况是因为文本文件第2行上的空行.
./ccwc.o -l small.txt
0 0 0
3
24
127
我如何才能提高?
if (isspace(line_buffer[i]) && !isspace(line_buffer[i-1])){
word_count++;
}
才能抓住这个边缘 case ?