Skip to content

Instantly share code, notes, and snippets.

@w3ttr3y
Created January 8, 2016 23:12
Show Gist options
  • Save w3ttr3y/167b349d2ab67e3aa9d2 to your computer and use it in GitHub Desktop.
Save w3ttr3y/167b349d2ab67e3aa9d2 to your computer and use it in GitHub Desktop.
#include <stdlib.h>
#include <stdio.h>
#include <limits.h>
#include <fcntl.h>
#include <errno.h>
int main(int argc, char **argv) {
//##################
//## Parse Arguments (primitive)
//####################
ulong write_iterations = 0;
ulong iterations = ULONG_MAX;
if ( argc < 4) {
printf("%s tempFile realFile sampleFile\n", argv[0]);
exit(7);
}
char * tempFile = argv[1];
char * realFile = argv[2];
char * sampleFile = argv[3];
if ( argc > 4) {
char *pEnd;
write_iterations = strtoul(argv[4],&pEnd,10);
if ( argc > 5) {
iterations = strtoul(argv[5], &pEnd, 10);
}
}
//########################
//## Read Sample File
//#########################
char * buffer = 0;
long length;
FILE * f = fopen (sampleFile, "rb");
if (!f) {
printf("Unable to open sample file (%s)", sampleFile);
exit(9);
}
// Get the size of the sample file
fseek (f, 0, SEEK_END);
length = ftell (f);
fseek (f, 0, SEEK_SET);
buffer = malloc (length);
if(!buffer) {
printf("Unable to allocate buffer for sample file\n");
exit(8);
}
fread (buffer, 1, length, f);
fclose (f);
// If the realFile of the tempFile exist, remove them
// We want a clean test environment
remove(tempFile);
remove(realFile);
// We're about to hit the real stuff
// Loop over this a bunch of times to increase the chances we trigger the issue
ulong i = 0;
for ( i = 0 ; i < iterations ; i++) {
// See if we should write out how many iterations we've performed
if ( write_iterations != 0 )
if ( i % write_iterations == 0) {
printf("\rIteration %10lu", i);
fflush(stdout);
}
/////////////////////////////////////////////////////
/// The Main Event
//////////////////////////////////////////////////////
// Open file O_RDWR|O_CREAT|O_EXCL|O_TRUNC 0600
int fp = open(tempFile, O_RDWR|O_CREAT|O_EXCL|O_TRUNC, S_IRUSR | S_IWUSR);
// Write
write( fp, buffer, length );
// Close
close(fp);
// Link Actual file to temp file
int l = link(tempFile, realFile);
if( l != 0) {
printf("Huston, we have a problem linking the files (%s) -> (%s)", tempFile, realFile);
exit(6);
}
// Unlink Temp File
int r = remove(tempFile);
if(r != 0) {
printf("Huston, we have a problem (removing tempFile)\n");
exit(5);
}
// Stat file and ensure it is the expected size
struct stat st;
if(stat(realFile, &st) != 0) {
printf("File Error Message = %s\n", strerror(errno));
exit(3);
} else if (st.st_size != length) {
exit(4);
}
// Cleanup
remove(realFile);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment