Original Post
Hi,
I''m sure that this question is so simple, I''m going to kick myself if someone answers it.
Anyway, I''m trying to manipulate a file by asking the user to enter some info, based on their name, if their already exists in the file, the program should go to that record position and overwrite it with hte new record. But the problem with my code is that everytime I try it, the new record is appended at the end and the old record remains.
I''m using C++ to get the filepos (fp.tellg()
of the record to overwrite, then using this to go to this postion in the file and writing the new record, but it don''t wurk !!!
Here''s the source:
any help please.
djsomers
#include <conio.h>
#include <iostream.h>
#include <fstream.h>
const char *filename="testfile.txt\0";
const char *fileformat="testfileformat\0";
char username[256]="\0";
char filefmt[15]="\0";
const char *temusername="testname2\0";
int filepos;
bool overwrite=false;
struct recordout
{
char username[256];
short dummy;
}recout;
struct recordin
{
char username[256];
short dummy;
}recin;
bool createfile()
{
cout <<"\nPlease enter your name: ";
cin >> username;
// place user values in record
strcpy(recout.username,username);
recout.dummy=45;
fstream fp;
char userin;
// check if file exists by opening for reading
fp.open(filename,ios::in|ios::binary);
if(!fp)
{
// create file for writing
fp.open(filename,ios::out|ios::binary);
if(!fp)
return false;
fp.write(fileformat,strlen(fileformat)+1);
}
else
{
// check file format
fp.read(filefmt, sizeof filefmt);
if(strcmp(filefmt,fileformat)!=0)
return false;
// search for corresponding username in file
while(fp.read((char*)&recin,sizeof recin))
{
if(strcmp(recin.username,username)==0)
{
do
{
cout << "\n\nDo you wish to overwrite previous entry: ";
cin >> userin;
}while(userin !=''y'' && userin !=''n'');
// overwrite
if(userin==''y'')
{
// get the current location in the file
filepos=fp.tellg();
// go to the location in the file minus the rec structure
fp.seekg(filepos-258,ios::beg);
// store current location of file pointer
filepos=fp.tellg();
fp.close();
overwrite=true; // user wishes to overwrite record
}
else
{
fp.close();
return true;
}
}
}
}
if(overwrite)
{
// open file for writing
fp.open(filename,ios::app|ios::binary);
if(!fp)
return false;
fp.seekg(filepos,ios::beg); // go to location of username (record to overwrite)
fp.write((char*)&recout,sizeof recout);
fp.close();
return true;
}
else
{
// close open file
fp.close();
// file already exists, enter new user data
fp.open(filename,ios::app|ios::binary);
if(!fp)
return false;
// clear eof flag
if(fp.eof())
fp.clear();
// goto end of file
fp.seekg(0,ios::end);
fp.write((char*)&recout,sizeof recout);
fp.close();
}
return true;
}
void main()
{
if(createfile())
cout << "\n\nOK";
else
cout << "\n\nError";
getch();
}
|