Skip to content

Instantly share code, notes, and snippets.

@prasmussen
Last active December 11, 2015 00:19
Show Gist options
  • Save prasmussen/4515656 to your computer and use it in GitHub Desktop.
Save prasmussen/4515656 to your computer and use it in GitHub Desktop.
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <assert.h>
#include <string.h>
#include <fcntl.h>
#define MB 1000 * 1000
#define GB 1000 * MB
#define FNAME "test.data"
int write_data(char *fname, char *data) {
// Open file
int fd = open(fname, O_RDWR|O_CREAT|O_TRUNC, 0660);
assert(fd != -1);
int total_bytes = 0;
while (total_bytes < GB) {
// Write 1 MB of data to the file
int bytes = write(fd, data, MB);
total_bytes += bytes;
assert(bytes == MB);
}
close(fd);
// Make sure that we have written 1GB of data
assert(total_bytes == GB);
return total_bytes;
}
int verify_data(char *fname, char *data) {
// Allocate a buffer to store data read from file
char *buffer = malloc(MB);
assert(buffer != NULL);
// Open file
int fd = open(fname, O_RDONLY);
assert(fd != -1);
int total_bytes = 0;
while (total_bytes < GB) {
// Read 1 MB of data from the file
int bytes = read(fd, buffer, MB);
total_bytes += bytes;
assert(bytes == MB);
// Verify the data -- buffer and data should contain the same data
assert(memcmp(buffer, data, MB) == 0);
// Reset the buffer by overwriting with null characters
memset(buffer, '\0', MB);
}
close(fd);
free(buffer);
// Make sure that we have read 1GB of data
assert(total_bytes == GB);
return total_bytes;
}
int main(int argc, char *argv[]) {
// Allocate 1MB of data on the heap and fill it with a's
// This is our test data which will be written to disk
char *data = malloc(MB);
assert(data != NULL);
memset(data, 'a', MB);
int count = 0;
while (1) {
char fname[128];
sprintf(fname, "%s.%05d", FNAME, count++);
// Write 1 GB of data to a file
// The data is written in chunks of 1MB at the time
int bytes_written = write_data(fname, data);
// Read 1GB of data from the same file and verify that the data hasnt changed
// The data is read in chunks of 1MB at the time
int bytes_read = verify_data(fname, data);
printf("Wrote %d bytes and verified %d bytes, no errors found!\n", bytes_written, bytes_read);
}
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment