Untitled
unknown
c_cpp
2 years ago
2.7 kB
5
Indexable
#define _GNU_SOURCE #include <stdio.h> #include <stdlib.h> #include <sys/mman.h> #include <fcntl.h> #include <ctype.h> #include <unistd.h> #include <sys/types.h> #include <sys/stat.h> #define FILE_SIZE (500 * 1024 * 1024) // 500 MiB #define PAGE_SIZE sysconf(_SC_PAGESIZE) #define CHUNK_SIZE (1024 * PAGE_SIZE) int main() { // Create an empty file text.txt int fd = open("text.txt", O_CREAT | O_RDWR, S_IRUSR | S_IWUSR); if (fd == -1) { perror("Failed to open text.txt"); return 1; } if (ftruncate(fd, FILE_SIZE) == -1) { perror("Failed to resize text.txt"); close(fd); return 1; } // Open /dev/random int random_fd = open("/dev/random", O_RDONLY); if (random_fd == -1) { perror("Failed to open /dev/random"); close(fd); return 1; } // Memory map text.txt for writing char *file_map = mmap(NULL, FILE_SIZE, PROT_WRITE, MAP_SHARED, fd, 0); if (file_map == MAP_FAILED) { perror("Failed to memory map text.txt"); close(fd); close(random_fd); return 1; } // Generate the content of text.txt char *current = file_map; int count = 0; while (count < FILE_SIZE) { char c; if (read(random_fd, &c, 1) == 1 && isprint(c)) { *current = c; current++; count++; } } // Unmap the file for writing munmap(file_map, FILE_SIZE); int total_count = 0; // Memory map text.txt for reading in chunks struct stat st; fstat(fd, &st); off_t file_size = st.st_size; for (off_t offset = 0; offset < file_size; offset += CHUNK_SIZE) { off_t map_size = (file_size - offset > CHUNK_SIZE) ? CHUNK_SIZE : (file_size - offset); char *chunk = mmap(NULL, map_size, PROT_READ | PROT_WRITE, MAP_SHARED, fd, offset); if (chunk == MAP_FAILED) { perror("Failed to memory map a chunk of text.txt"); break; } // Count the capital letters and replace them with lowercase letters in the chunk int capital_count = 0; for (int i = 0; i < map_size; i++) { if (isupper(chunk[i])) { chunk[i] = tolower(chunk[i]); capital_count++; } } total_count += capital_count; // Unmap the chunk munmap(chunk, map_size); } printf("Total capital letters: %ld\n", total_count); // Close the file and /dev/random close(fd); close(random_fd); return 0; }
Editor is loading...