Skip to content

Instantly share code, notes, and snippets.

@B-Con
Last active December 15, 2015 05:08
Show Gist options
  • Save B-Con/5206266 to your computer and use it in GitHub Desktop.
Save B-Con/5206266 to your computer and use it in GitHub Desktop.
Creates files filled with 0s until no more can be created. (Likely because the filesystem is full.) This allows the filesystem image to be compressed quickly and easily for backups.
#include <stdio.h>
#include <sstream>
#include <string>
#include <vector>
#include <cstring>
typedef unsigned char BYTE;
#define TMP_FILENAME_BASE "TMP_ZERO_FILE_"
#define TMP_FILE_GROW_SIZE (1024*1024*16) // = 16 MB
#define MAX_EMPTY_FILES 10
using namespace std;
// Optional arg 2 specifies the destination dir to fill with zeroed files.
int main(int argc, char *argv[])
{
FILE *fp = NULL;
vector<string> TmpFileList;
int FileCreatedCtr = 0;
BYTE *ZeroMem = NULL;
bool bSuccessOpeningFile = true;
bool bCreatedFileZeroSize = false;
char *strBasePath;
if (argc == 2)
strBasePath = argv[1];
else
strBasePath = ".";
if ((ZeroMem = new BYTE[TMP_FILE_GROW_SIZE]) == NULL)
return(-1);
memset(ZeroMem, 0, TMP_FILE_GROW_SIZE);
// Create as many temp files as needed.
for ( ; bSuccessOpeningFile && !bCreatedFileZeroSize; FileCreatedCtr++) {
ostringstream ss;
string TmpFileName;
ss << FileCreatedCtr;
TmpFileName = strBasePath;
TmpFileName += "/";
TmpFileName += TMP_FILENAME_BASE;
TmpFileName += ss.str();
if ((fp = fopen(TmpFileName.c_str(), "wb")) != NULL) {
// Fill the file as full as possible.
while (fwrite(ZeroMem, sizeof(BYTE), TMP_FILE_GROW_SIZE, fp)
== TMP_FILE_GROW_SIZE); // Empty loop.
fseek(fp, 0, SEEK_END);
long FileSize = ftell(fp);
fclose(fp);
if (FileSize == 0)
bCreatedFileZeroSize = true;
printf("Created temp file %s of size %ld\n", TmpFileName.c_str(), FileSize);
TmpFileList.push_back(TmpFileName);
}
else {
bSuccessOpeningFile = false;
}
}
// Delete all the temp files.
bool bRemovedAll = true;
for (vector<string>::iterator it = TmpFileList.begin(); it != TmpFileList.end(); it++) {
if (remove(it->c_str()) != 0) {
fprintf(stderr, "Error deleting file %s\n", it->c_str());
bRemovedAll = false;
}
}
if (bRemovedAll)
printf("Successfully removed all temp files.\n");
return(0);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment