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,853 questions

51,774 answers

573 users

How to write int array to a binary file, and read int array from binary file in C

1 Answer

0 votes
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
 
#define SIZE 10

void print_arr(int arr[]);
 
int main(void)
{
    int arr[SIZE] = { 0 }; 
    int i;
    FILE *fp;
    
    srand(time(NULL));
    
    // Write int array to binary file
    fp = fopen("d:\\data.bin","wb");
    if (!fp)
    {
        printf("Unable to open file");
        return 1;
    }
     
    for (i = 0; i < SIZE; i++)
        arr[i] = rand() % 100 + 1;
    
    fwrite(arr, sizeof(arr[i]), SIZE, fp);
    
    print_arr(arr); // random numbers
     
    fclose(fp);

    // Read int array to binary file
    fp = fopen("d:\\data.bin","rb");
    if (!fp)
    {
        printf("Unable to open file");
        return 1;
    }
    
    for (i = 0; i < SIZE; i++)
        arr[i] = 0;
    
    print_arr(arr); // zero numbers
    
    fread(arr, sizeof(arr[i]), SIZE, fp);

    print_arr(arr); // same random numbers as above
    
    fclose(fp);
    
    return 0;
}
void print_arr(int arr[])
{
    int i;
    for (i = 0; i < SIZE; i++)
         printf("arr[%d] = %d\n", i, arr[i]);
}


/*
run:

arr[0] = 94
arr[1] = 90
arr[2] = 90
arr[3] = 64
arr[4] = 39
arr[5] = 6
arr[6] = 23
arr[7] = 65
arr[8] = 13
arr[9] = 69
arr[0] = 0
arr[1] = 0
arr[2] = 0
arr[3] = 0
arr[4] = 0
arr[5] = 0
arr[6] = 0
arr[7] = 0
arr[8] = 0
arr[9] = 0
arr[0] = 94
arr[1] = 90
arr[2] = 90
arr[3] = 64
arr[4] = 39
arr[5] = 6
arr[6] = 23
arr[7] = 65
arr[8] = 13
arr[9] = 69

*/


answered Oct 21, 2014 by avibootz
edited Oct 22, 2014 by avibootz

Related questions

1 answer 130 views
1 answer 136 views
2 answers 193 views
2 answers 221 views
1 answer 174 views
...