Here is an example of what I'm attempting, on a larger scale.
Code:
#include <iostream>
#include<string>
#include<sstream>
#include<sys/mman.h>
#include<sys/types.h>
#include<sys/stat.h>
#include<fcntl.h>
#include<cstdlib>
#include<cstring>
void set_field(int n,void* m_ptr,const std::string& data, int field_width)
{
memcpy(static_cast<char*>(m_ptr)+n*sizeof(char)*field_width,data.c_str(),field_width);
}
std::string get_field(int n,void* m_ptr, int field_width)
{
char data[field_width];
memcpy(data,static_cast<char*>(m_ptr)+n*sizeof(char)*field_width,field_width);
return std::string(data);
}
int main()
{
std::string filename;
int file_size = 256;//Kb
int field_width = 8;//bytes
std::cout<<"Filename : ";
std::cin>>filename;
std::ostringstream dd_command;//"dd if=/dev/zero of=$filename count=$file_size bs=1024"
dd_command<<"dd if=/dev/zero of="<<filename<<" count="<<file_size<<" bs=1024 2>/dev/null";
system(dd_command.str().c_str()); // Any other way to do this ?
int fd = open(filename.c_str(),O_RDWR);
auto ptr=mmap(0,file_size*1024,PROT_READ|PROT_WRITE,MAP_SHARED,fd,0);
if(fd==-1 || ptr==nullptr)return -1;
set_field(6,ptr,"Manasij",field_width);
std::cout<<get_field(6,ptr,field_width);
munmap(ptr,file_size*1024);
close(fd);
return 0;
}
I'm creating an empty file of a given size and mapping it, to put a specific value somewhere within it and retrieve it.
I'll map small subsections of the file when doing this on large files, but other than that, is there anything wrong here ?