I have a list of categories seperated by newlines in a file cats.txt
I'm trying to write code that takes each category name and adds it to an array (of category strings). You can see from the output that it isn't doing what it should be.
Here is the file cats.txt
And here is main.c
And when I run it...
Can anyone explain what is going on?
I'm trying to write code that takes each category name and adds it to an array (of category strings). You can see from the output that it isn't doing what it should be.
Here is the file cats.txt
Code:
apples
oranges
bananas
And here is main.c
Code:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main(int argc, char *argv[])
{
FILE * fp = fopen("cats.txt", "r");
char * line = malloc(80);
char * *category_list = malloc(100); // 100 chosen arbitrarily...
int i = 0;
while (fgets(line, MAX_STRING_LENGTH, fp) != 0) {
/* Remove trailing '\n' from line */
*(line + strlen(line) - 1) = '\0';
/* Add string to array */
*(category_list + i) = line;
i++;
}
printf("first line: %s\n", *(category_list + 0));
printf("second line: %s\n", *(category_list + 1));
printf("third line: %s\n", *(category_list + 2));
fclose(fp);
return 0;
}
And when I run it...
Code:
> ./main
first line: bananas
second line: bananas
third line: bananas
Can anyone explain what is going on?