This is the mail archive of the
gcc-bugs@gcc.gnu.org
mailing list for the GCC project.
Re: problems with seekp
- To: erickson71 at yahoo dot com
- Subject: Re: problems with seekp
- From: "Martin v. Loewis" <martin at loewis dot home dot cs dot tu-berlin dot de>
- Date: Thu, 30 Dec 1999 10:51:37 +0100
- CC: gcc-bugs at gcc dot gnu dot org
- References: <19991229095311.17174.qmail@web701.mail.yahoo.com>
> I'm having problems using seekp. I've read many
> manuals including the GNU docs. Can someone clarify
> whether this is a usage problem?
The usage of seekp is quite alright. There are two other problems:
- you open the file for reading without closing it first. As a result,
not all file contents is flushed.
- you try to read 10 bytes when only 8 bytes are available.
I'll attach a corrected version below.
Regards,
Martin
/////////////////////////////////////////////////////////////
// simple.cc: Record file I/O test program.
// Copyright(c) 1993 Azarona Software. All rights reserved.
/////////////////////////////////////////////////////////////
#include <string.h>
#include <fstream.h>
#include <iostream.h>
char *fred = "Fred";
char *ebenezer = "Ebenezer";
char persona[20];
main()
{
ofstream ofs;
ifstream ifs;
/* Write */
ofs.open("test.fil", ios::out | ios::nocreate);
if (ofs) {
ofs.write(fred, strlen(fred));
ofs.seekp(0, ios::beg);
if (!ofs) {
cout << "Error seeking\n";
}
if (ofs) ofs.write(ebenezer, strlen(ebenezer));
if (!ofs) {
cout << "Error writing to file\n";
}
}
else {
cout << "Error opening file\n";
}
ofs.close();
/* Read */
ifs.open("test.fil", ios::in);
if (ifs) {
cout << "Reading in data for persona\n";
ifs.read(persona, 8);
if (ifs) {
cout << persona << '\n';
} else {
cout << "Error reading persona\n";
}
}
else {
cout << "Error reopening file\n";
}
return 0;
}