Skip to content

Instantly share code, notes, and snippets.

@massenz
Created September 4, 2013 23:05
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save massenz/6444010 to your computer and use it in GitHub Desktop.
Save massenz/6444010 to your computer and use it in GitHub Desktop.
A simple implementation of the Linux `truncate` function - this is missing in Mac OSX so I decided to implement it. The binary is a Release build for Mac OSX 10.8.4; should run in most versions.
/*
* truncate.cpp
*
* Created on: Sep 4, 2013
* Author: marco
*/
#include <iostream>
#include <stdio.h>
#include <unistd.h>
using namespace std;
// Prints usage for this application
void usage() {
cout << "Usage: truncate [-s SIZE] file" << endl;
cout << endl << "\tSIZE in bytes is the desired size for the file,"
" 0 by default" << endl;
}
// This is a super-simplified implementation of Linux's `truncate` bash
// functionality - it only supports the -s SIZE argument.
//
// Use with care: if the argument following the -s cannot be parsed into a valid
// integer format, it will truncate the file to 0 bytes
int main(int argc, char* argv[]) {
if (argc < 2) {
usage();
exit(1);
}
long size = 0;
int file_index = 1;
if (strcmp(argv[1], "-s") == 0) {
size = atol(argv[2]);
file_index = 3;
}
char *fname = argv[file_index];
cout << "Truncating " << fname << " to " << size << " bytes length" << endl;
if (truncate(fname, size) != 0) {
cerr << "Could not truncate file " << fname << " to " << size << " bytes" << endl;
exit(1);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment