Code:
#include <stdio.h>
#include <stdlib.h>
#include <getopt.h>
#include <dirent.h>
#include <pthread.h>
char* program_name;
char program_path[PATH_MAX + 1];
struct Foo {
FILE *file_content;
char* character;
};
// funkcia pre vypis HELPu //
void print_help(FILE *stream, int exit_code) {
// help goes here //
exit(exit_code);
}
void GetCurrentPath(char* buffer) {
getcwd(buffer, (PATH_MAX + 1));
}
int my_assert(int exp, char* msg, int do_abort, char* program_name, int line_number) {
if ( !(exp) ) {
GetCurrentPath(program_path);
fprintf(stderr, "Error in directory %s, in file %s, in program %s, on line c.%d\n", program_path, __FILE__, program_name, line_number);
fprintf(stderr, "Popis chyby: %s\n\n", msg);
if ( do_abort ) {
abort();
}
return 1;
} else {
return 0;
}
}
void* count_character(void* arg) {
struct Foo *f = (struct Foo*) arg;
const int string_length = 10;
char buffer[string_length];
int i=0, character_count = 0;
while( fgets(buffer, string_length, f->file_content) != NULL ) {
for ( i=0; i<string_length; i++ ) {
if ( buffer[i] == '\0' ) {
break;
} else {
if ( buffer[i] == *f->character ) {
character_count++;
}
}
}
}
return (void*) character_count;
}
int main(int argc, char *argv[]) {
FILE *file_content;
program_name = argv[0];
int next_option;
struct Foo *f;
pthread_t thread;
if (system("cls")) {
system("clear");
}
const char* const short_options = "h";
const struct option long_options[] = {
{"help", 0, NULL, 'h'},
{NULL, 0, NULL, 0}
};
do {
next_option = getopt_long(argc, argv, short_options, long_options, NULL);
switch (next_option) {
// program pre argument h/help //
case 'h':
print_help(stdout, 0);
case '?':
fprintf(stderr, "Unknown argument\n\n");
print_help(stderr, 1);
case -1:
if (argc == 3) {
file_content = fopen(argv[1], "r");
if (my_assert((file_content != NULL), "Cannot open file.", 0, program_name, __LINE__)) {
printf("Cannot open file %s\n", argv[1]);
exit(1);
}
f->file_content = file_content;
f->character = argv[2];
int result;
int tc = pthread_create(&thread, NULL, &count_character, (void*) &f);
if (my_assert((tc == 0), "Thread does not create.", 0, program_name, __LINE__)) {
printf("Thread does not create\n");
exit(1);
}
pthread_join(thread, (void*) &result);
fprintf(stdout, "Result is: '%d'\n", result);
fclose(file_content);
exit(0);
} else {
fprintf(stderr, "Error: argument count '%d'\n\n", argc-1);
print_help(stderr, 1);
}
default:
fprintf(stderr, "Unexpected error\n");
abort();
}
}
while (next_option != -1);
return (0);
}
And result is segmentation fault. I really dont know where is the problem. If I try to echo file content in count_character function it gives me some characters there wasn't in file.