Created
September 4, 2013 23:05
-
-
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.
This file contains 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
/* | |
* 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