#include #include #include #include #include #include #define FILENAME ".charfreq" int main(int argc, char ** argv){ char filename[128]; snprintf(filename, 128, "%s/%s", getenv("HOME"), FILENAME); int fd = open(filename, O_RDWR); unsigned int *counts; if(fd == -1 /* The file does not exist */ ){ /* Create the file and initialize counts to 0 */ printf("Initializing %s\n", filename); fd = open(filename, O_RDWR | O_CREAT, 0644); unsigned int zero = 0; for(unsigned int i = 0; i < 256; i++) write(fd, &zero, 4); } counts = mmap(0, 1024, PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0); if(counts == MAP_FAILED){ perror("mmap"); return 1; } if(argc > 1 && !strcmp(argv[1], "-p")){ for(unsigned int i = 0; i < 256; i++) printf("Character %u(%c): %u\n", i, i, counts[i]); return 0; } /* Read from standard in and add to character array */ unsigned char buffer[1024]; ssize_t readlen; while(readlen = read(0, buffer, 1024)){ /* Process readlen characters */ for(int i = 0; i < readlen; i++){ counts[buffer[i]]++; } } munmap(counts, 1024); return 0; }