Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Buy a domain name - Register cheap domain names from $0.99 - Namecheap

Scalable Hosting That Grows With You

Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Semrush - keyword research tool

Boost your online presence with premium web hosting and servers

Disclosure: My content contains affiliate links.

39,855 questions

51,776 answers

573 users

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 134 views
2 answers 166 views
2 answers 443 views
443 views asked Oct 18, 2014 by avibootz
1 answer 216 views
1 answer 181 views
...