This is the mail archive of the gcc-bugs@gcc.gnu.org mailing list for the GCC project.


Index Nav: [Date Index] [Subject Index] [Author Index] [Thread Index]
Message Nav: [Date Prev] [Date Next] [Thread Prev] [Thread Next]

Re: problems with seekp


> 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;
}


Index Nav: [Date Index] [Subject Index] [Author Index] [Thread Index]
Message Nav: [Date Prev] [Date Next] [Thread Prev] [Thread Next]