Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /**
- * A C program to demonstrate the reading a file line by line.
- *
- * "config.txt" must exist at the root of the project.
- * contains #,#,#,#,#
- *
- * @author Nicholas Adamou
- * @date 12/7/2019
- */
- #include <stdio.h>
- #include <stdlib.h>
- #include <string.h>
- typedef struct TestCase TestCase;
- struct TestCase {
- int BSIZE;
- };
- char **split(char *str, const char separator);
- TestCase *createTestCase(char *data);
- TestCase **readFile(char *path, int number_of_test_cases);
- TestCase *createTestCase(char *data) {
- TestCase *test_case = (TestCase *)malloc(sizeof(TestCase));
- test_case->BSIZE = atoi(&data[0]);
- return test_case;
- }
- char **split(char *str, const char separator)
- {
- char **result = 0;
- size_t count = 0;
- char *tmp = str;
- char *last_comma = 0;
- char delim[2];
- delim[0] = separator;
- delim[1] = 0;
- // Count how many elements will be extracted.
- while (*tmp)
- {
- if (separator == *tmp)
- {
- count++;
- last_comma = tmp;
- }
- tmp++;
- }
- // Add space for trailing token.
- count += last_comma < (str + strlen(str) - 1);
- // Add space for terminating null string so caller
- // knows where the list of returned strings ends.
- count++;
- result = malloc(sizeof(char *) * count);
- if (result)
- {
- size_t i = 0;
- char *token = strtok(str, delim);
- while (token)
- {
- result[i++] = strdup(token);
- token = strtok(NULL, delim);
- }
- result[i] = 0;
- }
- return result;
- }
- TestCase **readFile(char *path, int number_of_test_cases)
- {
- FILE *file = fopen(path, "r");
- if (file)
- {
- TestCase **test_cases = (TestCase **)malloc(sizeof(TestCase) * number_of_test_cases);
- char *line;
- size_t length;
- size_t read;
- int index = 0;
- while ((read = getline(&line, &length, file)) != -1)
- {
- printf("%s", line);
- char **data = split(line, ',');
- test_cases[index++] = createTestCase(line);
- }
- fclose(file);
- return test_cases;
- }
- return NULL;
- }
- int main(int argc, char **argv)
- {
- TestCase **data = readFile("./config.txt", 200);
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment