I'm trying to create a train station simulation for an assignment at school in C. This is an exercise in understanding threaded programming. Here is my current code:
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
#include <string.h>
#include <readline/readline.h>
void *train_function(void *args) {
printf("Train created!\n");
pthread_exit(0);
}
int main() {
FILE *ptr_file;
char buff[10];
int ch;
int train_count = 0;
ptr_file = fopen("./trains.txt", "r");
if (!ptr_file)
return 0;
/* Count number of trains */
while(!feof(ptr_file))
{
ch = fgetc(ptr_file);
if(ch == '\n')
{
train_count++;
}
}
pthread_t trains[train_count];
/* Create train for each line of file */
int train_index = 0;
while (fgets(buff,10, ptr_file)!=NULL) {
pthread_create(&trains[train_index], NULL, train_function, NULL);
train_index++;
}
fclose(ptr_file);
/* Wait for all trains to leave the station */
for (int x = 0; x < train_count; x++) {
pthread_join(trains[x], NULL);
}
exit(0);
}
The code reads information about trains from a file trains.txt and creates a new thread for each line of the file(each train).
e:10,6
W:5,7
E:3,10
I would expect the output to be "Train Created!" three times. Compiling the code produces a Segmentation fault. What am I missing?