finding the end of a line of a file.
I'm reading in a file line by line. Each line has a name, and a random number of classes.
for example
Jerry,CSE1310,CSE1320,CSE1325
Bob,CSE1105,CSE1310
Barry,CSE1104,CSE1105,CSE1310,CSE1320
These are the names and the classes they have already taken.
I'm trying to tread this file and store in a 2d array of strings. The first column will be the names and the following columns are the classes taken. My question is, since the number of classes is not definite, how do I create a loop to do this until the newline?
Here's what I have so far, but it's not working. I think my second while loop is where I'm messing up. I think it's a never ending loop because I'm not changing buffer. Just wondering how to basically say while it's not the end of the line, keep using strtok on the commas and put in the next column.
Code:
FILE *fp;
char buffer[100];
int line_count = 0;
int class_count = 0;
char *temp;
char **names_and_classes_taken = malloc (sizeof(char*));
if ( (fp = fopen("hw11-data.csv", "r" )) == NULL )
{
printf("Couldn't open file\n");
exit(1);
}
while(fgets(buffer, sizeof(buffer), fp))
{
while ( strcmp(buffer, " \n") != 0)
{
/* if class count is 0, use the buffer, else if the count is
not 0, use the same buffer */
if(class_count == 0)
temp = strtok(buffer, ",");
else
temp = strtok(NULL, ",");
names_and_classes_taken[class_count] = malloc(strlen(temp));
strcpy(names_and_classes_taken[class_count], temp);
}
class_count = 0;
line_count++;
names_and_classes_taken = realloc(names_and_classes_taken, (line_count+1)* sizeof(char*));
}
fclose(fp);