Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <stdio.h>
- #include <unistd.h>
- #include <pthread.h>
- #include <string.h>
- #define MAX_FILES_COUNT 1000
- #define MAX_LINE_LENGTH 10000
- #define OUT 0
- #define IN 1
- struct file_info {
- char* file_name;
- FILE* file_ptr;
- };
- int total_lines, total_words, total_chars;
- pthread_mutex_t mutex;
- void* compute_word_count(void* args) {
- struct file_info* file = (struct file_info*) args;
- int lines, words, chars;
- char* file_name = file -> file_name;
- FILE* file_ptr = file -> file_ptr;
- lines = words = chars = 0;
- char buffer[MAX_LINE_LENGTH];
- while(fgets(buffer, sizeof(buffer), file_ptr) != NULL) {
- lines++;
- int i = 0;
- int state = OUT;
- while(buffer[i] != '\0') {
- chars++;
- if(buffer[i] == ' ' || buffer[i] == '\t' || buffer[i] == '\n')
- state = OUT;
- else if(state == OUT) {
- words++;
- state = IN;
- }
- i++;
- }
- }
- printf("%2d %4d %8d %16s\n", lines, words, chars, file_name);
- pthread_mutex_lock(&mutex);
- total_lines += lines;
- total_words += words;
- total_chars += chars;
- pthread_mutex_unlock(&mutex);
- }
- void get_word_count(struct file_info files[], int count) {
- pthread_t tid[MAX_FILES_COUNT];
- pthread_mutex_init(&mutex, NULL);
- for(int i = 0; i < count; i++) {
- pthread_create(&tid[i], NULL, &compute_word_count, &files[i]);
- }
- for(int i = 0; i < count; i++) {
- pthread_join(tid[i], NULL);
- }
- pthread_mutex_destroy(&mutex);
- printf("%2d %4d %8d %16s\n", total_lines, total_words, total_chars, "total");
- }
- int main(int argc, char* argv[])
- {
- FILE* file_ptr[MAX_FILES_COUNT];
- struct file_info files[MAX_FILES_COUNT];
- int valid_files = 0;
- if(argc - 1 > MAX_FILES_COUNT) {
- fprintf(stderr, "File count limit exceeded. Remove %d files.", argc - 1 - MAX_FILES_COUNT);
- }
- for(int i = 0; i < argc - 1; i++) {
- file_ptr[valid_files] = fopen(argv[i + 1], "r");
- if(file_ptr[valid_files] == NULL)
- fprintf(stderr, "File %s not found\n", argv[i + 1]);
- else {
- files[valid_files].file_ptr = file_ptr[valid_files];
- files[valid_files].file_name = argv[i + 1];
- valid_files++;
- }
- }
- get_word_count(files, valid_files);
- for(int i = 0; i < valid_files; i++) {
- fclose(file_ptr[i]);
- }
- return 0;
- }
Advertisement
Comments
-
- Find the blog at https://syedumair327.blogspot.com
Add Comment
Please, Sign In to add comment