Reputation: 87
I am creating a program that reads numbers from a file, gets the amount of numbers, creates an array and displays those numbers along with the amount of numbers in the file. I am using fscanf to get the the data from the file. I finally got the program to compile and output but it only reads 4 out of the 10 numbers in the files. If I increase the amount of numbers it still only reads 4 number. If I decrease the amount of numbers to below 4 its still tries to read 4 numbers and the prints random numbers from memory. I think that its a pointer issue but I'm still new and don't fully understand pointers. Help is appreciated.
Code:
#include <stdio.h>
#include <stdlib.h>
int ReadSize (FILE*);
void readData(FILE* fp, int size, int* arr1);
int* allocateMemory(int);
int main (int argc, char* argv[])
{
FILE * in = fopen(argv[1], "r"); //Gets file to read
int size = ReadSize(in);
printf("Size: %i\n", size); //Temp Line to Print Size
int *arr1 = allocateMemory(size);
readData(in, size, arr1);
printf("Data: ");
for (int i = 0; i < size; i++)
{
printf("%d, ", arr1[i]);
}
}
int ReadSize(FILE* fp)
{
int size = 0;
fscanf(fp, "%d", &size);
return size;
}
void readData(FILE* fp, int size, int* arr1)
{
int i;
for(i = 0; i < size; i++)
{
fscanf(fp, "%d", &arr1[i]);
}
}
int* allocateMemory(int sz)
{
int *temp = (int*)malloc(sizeof(int)*sz);
return temp;
}
Input File:
4 2
-1 2
1 2
2 -1
-1 -2
Upvotes: 0
Views: 231
Reputation: 121649
I think you're misinterpreting the file format. You read "4" from the file, then your loop iterates 4 times: hence 4 numbers, not 10.
But we can only guess what you SHOULD read.
Perhaps something like this:
#include <stdio.h>
#include <stdlib.h>
int main (int argc, char* argv[])
{
FILE *in;
if ((fp = fopen(argv[1], "r")) == 0) {
printf("Error: unable to open file!\n");
return -1;
}
int nitems, items_per_line;
if (fscanf(fp, "%d %d", &nitems, &items_per_line) != 2) {
printf ("Error reading dimensions!\n");
return -1;
}
int *arr1 = malloc (sizeof(int) * nitems * items_per_line);
if (arr1 == 0) {
printf("Error: unable to malloc array!\n");
return 1;
}
for (int i = 0; i < nitems * items_per_line; i++) {
fscanf(fp, "%d", &arr1[i]);
}
return 0;
}
Or perhaps you'd be better served with an n-dimensional array (e.g. arr1[2][4])?
Again - without knowing more about the format, we can only guess...
PS: You should ALWAYS check for errors in your code!
Upvotes: 2
Reputation: 224864
The first thing your program does is try to read a decimal number from the file in ReadSize()
. That gets 4
, which then, as you describe, reads 4 numbers. You need to put a 10
at the top of your input file if you want it to match the format that program expects.
Upvotes: 1