Hi there,
I have created a function which accepts a pointer to a char array (unsigned char *insert) and inserts the corresponding byte values into a file (char *fname) at a specified position(unsigned long pos) with length(unsigned long insertlen). this appears to work ok. Does such a routine already exist ?
Anyway, this is part of a much larger program to build a database of repeating words/sequences in a file and their corresponding file positions. . . . . . .
However, I also need to insert a long into positions within the file, so I tried to convert it to a pointer to a char array, which is where errors occur, either in conversion or when *longvar is passed into the insertintofile function. For efficiency, I don't really want to split the long variable into 4 unsigned char's then to a pointer to an unsigned char array eg. *sequence in void main():
Code://this code causes the program to halt unsigned char *longvar=reinterpret_cast<unsigned char*>(wordpos); //wordpos=long var of file position of sequence insertintofile("testfile.dat", longvar, 10, sizeof(long));
This is the insertintofile test program & function:
Code:#include <iostream> //used for console input/output #include <fstream> //used for file input/output #include <io.h> //used to enable filelength checking #include <conio.h> //used to enable getch() function using namespace std; void insertintofile(char *fname, unsigned char *insert, unsigned long pos, unsigned long insertlen); void main () { unsigned char *sequence=new unsigned char[4]; *sequence=97; *(sequence+1)=98; *(sequence+2)=99; *(sequence+3)=100; insertintofile("testfile.txt", sequence, 10, 4); } void insertintofile(char *fname, unsigned char *insert, unsigned long pos, unsigned long insertlen) { fstream orig; fstream temp; orig.open(fname, ios::in | ios::out | ios::binary); temp.open("tempfile.dat", ios::out | ios::trunc | ios::binary); orig.seekg(pos, ios::beg); char ch=0; while (orig.get(ch)) temp.put(ch); temp.close(); orig.clear(); orig.seekp(pos, ios::beg); for (unsigned long insertpos=0; insertpos<insertlen; insertpos++) { int belter=*(insert+insertpos); cout << "belter=" << belter; orig.put(belter); } temp.open("tempfile.dat", ios::in | ios::binary); while (temp.get(ch)) orig.put(ch); orig.close(); temp.close(); remove("tempfile.dat"); }
Any help would be appreciated,
thanks
Gary



LinkBack URL
About LinkBacks



.