Read () errors caused by reading text bytes. read text
After several months of work, I had nothing to worry about and started reading the Classic C program design. When I saw the Character Count section, I thought I would use read () to read the text as the character input. everything was OK, when the row count problem occurs, there is no problem with the total number of characters, and the feasible calculation cannot be done. After thinking for a long time, I asked "Great God" to help me find the problem, the problem lies in the comparison of char and int in condition judgment:
The key to the problem is that read () is a direct write memory block. When reading a byte, only one byte is written to the address of one byte in the memory, when the int type is used to read data, the first three bytes of the result int are still in the junk data state, and it is not equal, the solution is to initialize int c to 0 at the beginning, or forcibly convert int to char type to avoid adding the first three junk data to the comparison.
The conclusion is that a good habit is really important and you must remember to initialize it.
1 #include <stdio.h> 2 #include <unistd.h> 3 #include <sys/types.h> 4 #include <fcntl.h> 5 6 int main(int argc, char **argv) 7 { 8 int fd; 9 long nc = 0;10 long lc = 0;11 long tc = 0;12 13 int c;14 int ret;15 16 printf("c = %c ,%08x %d %c\n", c,c,c,(char)(c));17 fd = open(argv[1], O_RDONLY);18 19 while ((ret = read(fd, &c, 1)) != 0) {20 printf("c = %c ,0x_c = %08x d = %d c_char = %c\n", c, c, c, (char)(c));21 nc++;22 if (c == ' ') {23 lc++;24 } else if (c == '\t') {25 tc++;26 }27 }28 29 printf("char count: %ld\n", nc);30 printf("line count: %ld\n", lc);31 printf("table count: %ld\n", tc);32 33 close(fd); 34 35 return 0;36 }