In your approach you are walking through the file once to determine the number of rows, then you try to read through it further even though you're already at the end. Also, the code you have gives too many rows. If sales.txt has 16 rows of data, your code tells me that it has 17.
Here's how I would do it. This determines the number of rows and then places your file pointer on the first row of data, ready for you to read in:
Code:#define FILENAME "sales.txt"
#define EXIT_FILE_ERROR (1)
#define EXIT_UNEXPECTED_EOF (2)
#define EXIT_INVALID_FIRSTLINE (3)
#define MAXLINE (10000)
char line[MAXLINE];
int main(void)
{
// Open file
FILE *fp;
if ((fp = fopen(FILENAME, "r")) == NULL)
exit(EXIT_FILE_ERROR);
// Figure out how many columns there are
int cols;
if ((fgets(line, sizeof(line), fp)) == NULL)
exit(EXIT_UNEXPECTED_EOF);
if ((sscanf(line, "%d", &cols)) != 1)
exit(EXIT_INVALID_FIRSTLINE);
// Read each line in the file to figure out how many rows there are
int rows = 0;
while ((fgets(line, sizeof(line), fp)) != NULL) {
if (strlen(line) == 1) // don't count blank lines
continue;
rows++;
}
// Rewind to beginning and then skip the first line
rewind(fp);
fgets(line, sizeof(line), fp);
// Allocate correctly-sized array
char array[rows][cols];
printf("number of rows is %d and number of columns is %d\n", rows, cols);
// TODO
fclose(fp);
return EXIT_SUCCESS;
}