Daily Archives: October 4, 2013
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]
C++ || Snippet – How To Use Memory Mapped Files
The following is sample code which demonstrates the use of the “mmap”, “munmap” and “getpagesize” function calls on Unix based systems.
A memory mapped file is a segment of virtual memory which has been assigned a direct byte for byte correlation with some portion of a file or file like resource. This resource is typically a file that is physically present on disk, but can also be a device, shared memory object, or other resource that the operating system can reference through a file descriptor.
The primary benefit of memory mapping a file is increasing I/O performance, especially when used on large files. Accessing memory mapped files is faster than using direct read and write operations for two reasons. Firstly, a system call is orders of magnitude slower than a simple change to a program’s local memory. Secondly, in most operating systems the memory region mapped actually is the kernel’s page cache (file cache), meaning that no copies need to be created in user space.
The following example demonstrates the use of the “mmap” to map a file into memory, and display its contents to the screen.
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 60 61 62 63 64 65 66 67 68 69 |
// ============================================================================ // Author: K Perkins // Date: Oct 4, 2013 // Taken From: http://programmingnotes.org/ // File: mmap.cpp // Description: Demonstrate the use of memory mapped files // ============================================================================ #include <iostream> #include <cstdlib> #include <unistd.h> #include <sys/mman.h> #include <fcntl.h> using namespace std; int main(int argc, char* argv[]) { // declare variables int fd = -1; int pagesize = -1; char* data = NULL; // check if theres enough commandline args if(argc < 2) { cerr<<"USAGE: "<<argv[0]<<" <FILE NAME>n"; exit(1); } // open the specified file fd = open(argv[1], O_RDWR); // check if the open was successful if(fd < 0) { cerr<<"open error (file not found)n"; exit(1); } // get the page size pagesize = getpagesize(); // map the file into memory data = (char*)mmap((caddr_t)0, pagesize, PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0); // did the mapping succeed ? if(!data) { cerr<<"mmap errorn"; exit(1); } // print the whole file character-by-character for(int x = 0; x < pagesize; ++x) { cerr<<data[x]; } // optional: write a string to the file //memcpy(data, "Hello world, this is a testn", sizeof("Hello world, this is a test")); // unmap the shared memory region munmap(data, pagesize); // close the file close(fd); 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:
./mmap mmap.cpp
[THE CONTENTS OF "MMAP.CPP" IS DISPLAYED TO THE SCREEN]
C++ || Snippet – How To Display The Size Of A File Using Stat
The following is sample code which demonstrates the use of the “stat” function calls on Unix based systems.
The stat function returns information about a file. No permissions are required on the file itself, but-in the case of stat() and lstat() – execute (search) permission is required on all of the directories in path that lead to the file.
The “stat” system call returns a stat structure, which contains the following fields:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
struct stat { dev_t st_dev; /* ID of device containing file */ ino_t st_ino; /* inode number */ mode_t st_mode; /* protection */ nlink_t st_nlink; /* number of hard links */ uid_t st_uid; /* user ID of owner */ gid_t st_gid; /* group ID of owner */ dev_t st_rdev; /* device ID (if special file) */ off_t st_size; /* total size, in bytes */ blksize_t st_blksize; /* blocksize for file system I/O */ blkcnt_t st_blocks; /* number of 512B blocks allocated */ time_t st_atime; /* time of last access */ time_t st_mtime; /* time of last modification */ time_t st_ctime; /* time of last status change */ }; |
The following example demonstrates the use of the “st_size” struct parameter to display the size of a file.
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 |
// ============================================================================ // Author: K Perkins // Date: Oct 4, 2013 // Taken From: http://programmingnotes.org/ // File: Stat.cpp // Description: Demonstrate the use of the "stat" function to display the // size of a file // ============================================================================ #include <iostream> #include <cstdlib> #include <unistd.h> #include <sys/types.h> #include <sys/stat.h> using namespace std; int main(int argc, char* argv[]) { // declare variables struct stat fileInfo; // the buffer to store file information // check to see if theres enough commandline args if(argc < 2) { cerr<<"n** ERROR - NOT ENOUGH ARGUMENTS!n" <<"nUSAGE: "<<argv[0]<<" <FILE NAME>n"; exit(1); } // get the file information if(stat(argv[1], &fileInfo) < 0) { cerr<<"nstat failed (file not found)n"; exit(1); } // display info to the screen cerr<<"nThe file ""<<argv[1]<<"" is "<<(int)fileInfo.st_size<<" bytesnn"; 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:
./Stat Stat.cpp
The file "Stat.cpp" is 1170 bytes