I have a program that reads a text file and uses fgets() to read line by line. I also used strtok_r() to tokenise each word that is seperated by a space. It works for the first line but then returns segmentation fault after.
Text file:
# execute a command at 3AM every day
0 3 * * * daily-backup
#
# execute a command at 4:15AM every Sunday
15 4 * * sun weekly-backup
#
# start thinking about the project....
0 10 22 7 mon deep-thought
#
# submit my project automatically, just in case I forget!
59 16 16 8 * submit-project
#
# mail out a monthly newsletter
0 2 1 * * send-monthly-newsletter
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main(int argc, char **argv)
{
char *filename = "crontab-file.txt";
FILE *pFile = fopen(filename, "r");
if (!pFile)
{
printf("error loading file '%s'\n", filename);
return 400;
}
fseek(pFile, 0, SEEK_END);
int size = ftell(pFile);
rewind(pFile);
char *buffer = (char *)malloc(sizeof(char) * (size + 1));
char *token;
while (fgets(buffer, (size + 1), pFile))
{
if (buffer[0] == '#')
continue;
while ((token = strtok_r(buffer, " ", &buffer)))
{
printf("Token: %s\n", token);
}
}
fclose(pFile);
return 0;
}