// sumbytes.c - sum bytes in a file, omitting {space, tab, CR, LF} // Randy Dunlap 2010.08.17 #include #include #include #include #include #include #include #include #define CR 0x0d #define LF 0x0a #define TAB 0x09 #define SPC 0x20 unsigned long countallbytes = 0; unsigned long countedbytes = 0; // not counting the omitted bytes unsigned long sumbytes = 0; int fd; char *filename; void usage(void) { fprintf(stderr, "usage: sumbytes file_name\n"); } void read_sum_bytes(void) { ssize_t bytes_read; int ix; unsigned char buf[16 * 1024]; unsigned char ch; while (bytes_read = read(fd, buf, sizeof(buf))) { for (ix = 0 ; ix < bytes_read; ix++) { countallbytes++; ch = buf[ix]; if (ch == CR || ch == LF || ch == SPC || ch == TAB) ; else { countedbytes++; sumbytes += ch; } } // end for ix } // end while bytes_read } // end read_sum_bytes; int main(int argc, char *argv[]) { if (argc != 2) { usage(); exit(0); } filename = argv[1]; fd = open(filename, O_RDONLY); if (fd < 0) { fprintf(stderr, "error %d: %s\n", errno, strerror(errno)); exit(1); } read_sum_bytes(); printf("for file '%s':\n", filename); printf("total number of bytes / number of counted bytes in file: %lu / %lu\n", countallbytes, countedbytes); printf("sum of counted bytes in file: %lu (0x%lx)\n", sumbytes, sumbytes); fd = close(fd); if (fd < 0) { fprintf(stderr, "error %d: %s\n", errno, strerror(errno)); exit(1); } exit(0); } // end main; // end sumbytes.c;