Created
May 10, 2016 15:06
-
-
Save kaworu/703526fb7934004218872aaa34741a5f to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <stdio.h> | |
#include <stdlib.h> | |
#include <errno.h> | |
#include <err.h> | |
// create array a of size n; fill with constant c | |
// write a to file in binary | |
// read back a from file | |
int main(){ | |
size_t n = 1e10; | |
int c = 1; | |
int *a = calloc(n, sizeof(int)); | |
if(a == NULL){ | |
err(1, "calloc"); | |
} | |
// fill array with constant c | |
for(size_t i = 0; i < n; i++) | |
a[i] = c; | |
FILE *fp = fopen("TMP.bin", "wb"); | |
if(fp == NULL){ | |
printf("error fopen\n"); | |
exit(1); | |
} | |
// write to binary | |
size_t n_write = fwrite(a, sizeof(int), n, fp); | |
if(n_write != n){ | |
perror("perror fwrite"); | |
} | |
fclose(fp); | |
free(a); | |
fp = fopen("TMP.bin", "rb"); | |
if(fp == NULL){ | |
printf("error fopen read\n"); | |
exit(1); | |
} | |
int *a_read = calloc(n, sizeof(int)); | |
if(a_read == NULL){ | |
printf("error calloc a_read\n"); | |
exit(1); | |
} | |
// read from file | |
size_t n_read = fread(a_read, sizeof(int), n, fp); | |
if(n_read != n){ | |
perror("perror fread"); | |
} | |
// compare to constant c | |
int i_error = 0; | |
for(size_t i = 0; i < n; i++){ | |
if(a_read[i] != c){ | |
printf("ERROR: a_read[%zu] = %d\n", i, a_read[i]); | |
i_error++; | |
if(i_error > 1e2) | |
break; | |
} | |
} | |
fclose(fp); | |
free(a_read); | |
if(i_error == 0){ | |
printf("Success!\n"); | |
} | |
} |
Author
kaworu
commented
May 10, 2016
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment