I made a simple program to input a text file into an array and then have have the user search for any number in the array. The search function works fine, I have tested it multiple times. But for some reason I cant get the text file to input into the array. Here is the code in the main c file:
Code:
#include <stdio.h>
#include <stdlib.h>
#include "search.h"
#include "filereader.h"
int main ()
{
FILE *ifp;
ifp = fopen("test.txt", "r");
int index, size, number, x, i;
printf("What number do you want to find?: ");
scanf("%d",&number);
size = 0;
i = 0;
while ((fscanf(ifp, "%d", &x)) == 1)
{
size++;
i++;
}
int *num = malloc(size * sizeof(int));
FileReader(ifp, num);
for(i = 0; i < size; i++)
printf("%d", num[i]);
index = Search(num, size, number);
fclose(ifp);
if(index != -1)
printf("Found it in index: %d\n", index);
else
printf("Didn't find it\n");
}
and here is the code for the file reader function:
Code:
#include <stdlib.h>
#include "filereader.h"
void FileReader(FILE *fp, int *numArray)
{
int i, x;
i = 0;
while ((fscanf(fp, "%d", &x)) == 1)
{
numArray[i] = x;
i++;
}
}
When i put the code that is in the FileReder function in main it works perfectly but when I try to use an outside function to read in the file it doesn't work. I ouput the array in main to see what it stored in it and it's always all 0's. Please help