C++ || Snippet – How To Create A File Of Any Size
The following is sample code which demonstrates how to create a file of any size using the fseek and fwrite function calls.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 |
// ============================================================================ // Author: K Perkins // Date: Oct 4, 2013 // Taken From: http://programmingnotes.org/ // File: createfileN.cpp // Description: Demonstrate how to create a file of any size // ============================================================================ #include <iostream> #include <cstdio> #include <cstdlib> #include <cstring> using namespace std; int main(int argc, char* argv[]) { // declare variables int fileSize = 0; FILE* fp = NULL; // check the command line arguments if(argc < 3) { cerr<<"n** ERROR NOT ENOUGH ARGS!n" <<"nUSAGE: "<<argv[0]<<" <FILE NAME> <FILE SIZE>nn"; exit(1); } // convert the file size from string to integer fileSize = atoi(argv[2]); // open the file to be created fp = fopen(argv[1], "w+"); // make sure the file was created ok if(!fp) { perror("open error"); exit(1); } // set the file marker to position N in the file (where N = file size) if(fseek(fp, fileSize - 1, SEEK_SET) < 0) { perror("fseek error"); exit(1); } // write a single byte to the file if(fwrite(" ", sizeof(char), strlen(" "), fp) < 0) { perror("write error"); exit(1); } // close the file fclose(fp); return 0; }// http://programmingnotes.org/ |
QUICK NOTES:
The highlighted lines are sections of interest to look out for.
The code is heavily commented, so no further insight is necessary. If you have any questions, feel free to leave a comment below.
The following is sample output:
./createfileN createfile.txt 12
[FILE "createfile.txt" IS CREATED AND IS 12 BYTES IN SIZE]
Was this article helpful?
👍 YesNo
Leave a Reply