This program is supposed to make two passes through a file; the first pass counts the number of elements inside the file to get the total size; the second pass will fill the array and sort it. The problem i'm having is that on the second pass, the array is filled with garbage. I tried to use rewind(), but my program crashes :eek: Here is the code:
/*
1. Get array dimensions and print array.
2. Create array based on total.
3. Fill AND sort array.
4. Print sorted array.
*/
#include <stdio.h>
#include <stdlib.h>
#define FILENAME "data.txt"
#define MODE "r"
int get_dim(FILE *);
int *make_array(int );
void fill_array(FILE *, int *, int );
void insertion(int *, int );
int main(void) {
FILE *fp = fopen(FILENAME, MODE);
int total = get_dim(fp);
int *array = make_array(total);
fill_array(fp, array, total);
return 0;
}
int get_dim(FILE *fp) {
int hold;
printf("*** File Contents ***\n\n");
for (int cnt = 0; fscanf(fp, "%d", &hold) != EOF; cnt++) {
printf("%3d ", hold);
if (cnt == 0)
continue;
if (cnt % 10 == 0)
printf("\n");
}
printf("\nTotal number of items: %d\n", cnt);
return cnt;
}
int *make_array(int total) {
int *array = (int *)malloc(sizeof(int) * total);
return array;
}
void fill_array(FILE *fp, int array[], int total) {
for (int cnt = 0; cnt < total; cnt++) {
if (fscanf(fp, "%d", array[cnt]) == 1)
insertion(array, cnt);
}
for (cnt = 0; cnt < total; cnt++) {
printf("%3d", array[cnt]);
if (cnt == 0)
continue;
if (cnt % 10 == 0)
printf("\n");
}
}
void insertion(int list[], int last) {
int walk;
int temp;
bool located;
for (int current = 1; current <= last; current++)
{
located = false;
temp = list[current];
for (walk = current - 1; walk >= 0 && !located;)
if (temp < list[walk])
{
list[walk + 1] = list[walk];
walk--;
}
else
located = true;
list[walk + 1] = temp;
}
return;
}