I am trying to write a simple program that reads in csv data from a text file, and then sums the values of the integers read in. I am new to C and trying to figure out small little programs to practice. I am able to get the file open, but it does not actually read in the values. Instead, it says the string read is simply the filename. I've been trying to figure it out. I know the actual code works because if I eliminate the file and input an array, it sums the values. Any ideas?
Here is the code:
#include <stdlib.h>
#include <string.h>
int main()
{
int x;
int sum;
char filename[] = "data.txt";
FILE *file = fopen(filename,"r");
char *ptr;
ptr = strtok(filename, ",");
sum = 0;
if (file == NULL)
{
printf("File could not be opened.\n");
getchar ();
}
else
{
while (ptr != NULL)
{
x = atoi(ptr);
printf("The string is: %s\n", ptr);
sum = sum + x;
ptr = strtok(NULL, ",");
}
fclose(file);
}
printf ("The sum of the numbers is: %d\n",sum);
getchar ();
}