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

51,780 answers

573 users

How to write a dynamic number of numbers to a binary file in C

2 Answers

0 votes
#include <stdio.h> 
#include <stdarg.h>
#include <stdlib.h> 

int writeToFile(char* filename, int first, ...) {
    FILE* fp = fopen(filename, "wb");

    if (!fp) { fputs("File open error", stderr); return 0; }

    va_list vl;

    va_start(vl, first);
    int n = first;

    while (n != 0) {
        fwrite(&n, sizeof(int), 1, fp);
        n = va_arg(vl, int);
    }

    fclose(fp);
    va_end(vl);

    return 1;
}

int readFile(char* filename) {
    FILE* fp = fopen(filename, "rb");
    if (!fp) { fputs("File open error", stderr); return 0; }
    
    int n;
    while (1) {
        fread(&n, sizeof(int), 1, fp);
        if (feof(fp)) break;
        printf("%d\n", n);
    }

    fclose(fp);

    return 1;
}


int main()
{
    char* filename = "d:\\data.bin";

    writeToFile(filename, 123, 8, 9, 100, 291073, 0);

    readFile(filename);

    return 0;
}



/*

run:

123
8
9
100
291073

*/

 



answered Apr 26, 2024 by avibootz
0 votes
#include <stdio.h> 
#include <stdarg.h>
#include <stdlib.h> 

int writeToFile(char* filename, int totalnumbers, ...) {
    FILE* fp = fopen(filename, "wb");

    if (!fp) { fputs("File open error", stderr); return 0; }

    int n;
    va_list vl;
    va_start(vl, totalnumbers);
    for (int i = 0; i < totalnumbers; i++) {
        n = va_arg(vl, int);
        fwrite(&n, sizeof(int), 1, fp);
    }

    fclose(fp);
    va_end(vl);

    return 1;
}

int readFile(char* filename) {
    FILE* fp = fopen(filename, "rb");
    if (!fp) { fputs("File open error", stderr); return 0; }
    
    int n;
    while (1) {
        fread(&n, sizeof(int), 1, fp);
        if (feof(fp)) break;
        printf("%d\n", n);
    }

    fclose(fp);

    return 1;
}


int main()
{
    char* filename = "d:\\data.bin";

    writeToFile(filename, 6, 123, 8, 9, 100, 291073, 45);

    readFile(filename);

    return 0;
}



/*

run:

123
8
9
100
291073
45

*/

 



answered Apr 26, 2024 by avibootz

Related questions

2 answers 158 views
1 answer 235 views
1 answer 195 views
1 answer 161 views
161 views asked Jul 24, 2015 by avibootz
1 answer 245 views
245 views asked Oct 17, 2014 by avibootz
2 answers 123 views
...