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

51,826 answers

573 users

How to write and read numbers from file in C

1 Answer

0 votes
#include <stdio.h>
#include <string.h>
 
int main(void) {
    char buffer_out[32];
    FILE *out = fopen("data.dat", "w");
    if (out == NULL) {
        return 1;
    }
     
    int a = 234, b = 9875;
    snprintf(buffer_out, 32, "%d %d\n", a, b);
    size_t bytes_wrote = fwrite(buffer_out, sizeof(int), strlen(buffer_out), out);
    fclose(out);
     
    if (bytes_wrote != strlen(buffer_out)) {
        return 1;
    }
	
	char buffer_in[32];
    FILE *in = fopen("data.dat", "r");
    if (in == NULL) {
        return 1;
    }
     
    if (fgets(buffer_in, 32, in) == NULL) {
        fclose(in);
        return 1;
    }
    fclose(in);
     
    int x, y;
    sscanf(buffer_in, "%d %d", &x, &y);
    printf("%d %d\n", x, y);
 
    return 0;
}
 
 
/*
data.dat
 
// 234 9875  @            ‰@     
 
*/
 
 
 
/*
run:
 
234 9875
   
*/

 



answered Dec 29, 2020 by avibootz

Related questions

1 answer 130 views
1 answer 139 views
1 answer 151 views
151 views asked Dec 30, 2020 by avibootz
1 answer 137 views
1 answer 76 views
...