How to read array of int numbers from binary file with fread() function in C

2 Answers

0 votes
#include <stdio.h>

#define N 4   
   
int main(void)
{
	int num_arr[N];
	// array that was written to file 
	//int num_arr[N] = { 10, 20, 30, 100 }; 
	
	FILE *fp = fopen("d:\\data.bin", "rb");

    if (fp == NULL) 
	{
		perror("Error open file");
		return 1;
	}
		 
	size_t result = fread (num_arr, 1, sizeof(int) * N, fp);
	if (result != sizeof(int) * N) 
	{
		printf("Error reading file");
		return 1;
	}
	
	fclose(fp);
	
	for (int i; i < N; i++)
		printf("%4d", num_arr[i]);
	
    return 0;
}
  
/*
run:
  
  10  20  30 100

*/

 



answered May 4, 2016 by avibootz
edited May 4, 2016 by avibootz
0 votes
#include <stdio.h>
#include <stdlib.h>

int main(void)
{
	int *num_arr_p;
	// array that was written to file 
	//int num_arr[N] = { 10, 20, 30, 100 }; 
	
	FILE *fp = fopen("d:\\data.bin", "rb");

    if (fp == NULL) 
	{
		perror("Error open file");
		return 1;
	}
	
	fseek(fp, 0, SEEK_END);
	long fsize = ftell(fp);
	rewind(fp);
	
	num_arr_p = (int *) malloc(sizeof(int) * fsize);
	if (num_arr_p == NULL) 
	{
		printf("malloc error");
		return 1;
	}
		 
	size_t result = fread(num_arr_p, 1, fsize, fp);
	if (result != fsize) 
	{
		printf("Error reading file");
		return 1;
	}
	
	fclose(fp);
	
	for (int i; i < fsize / sizeof(int); i++)
		printf("%4d", num_arr_p[i]);
		
	free(num_arr_p);
	
    return 0;
}
  
/*
run:
  
  10  20  30 100

*/

 



answered May 4, 2016 by avibootz
edited May 4, 2016 by avibootz

Related questions

2 answers 150 views
2 answers 189 views
2 answers 460 views
460 views asked Oct 18, 2014 by avibootz
1 answer 258 views
1 answer 204 views
...