Question

I want to be able to read and write into a file in the same instance or through same file handle. What I mean is this. Say you open a file as follows.

BinaryReader jfile := new BinaryReader(File.OpenRead('c:\jokes.dat'));

I want to be able to also write into the file without having to close the jfile handle and then call BinaryWriter to be able to write into the file. Can you do that?

Also, once you open a file to be written, any data in the old file with a same name will be completely erased. Is that true?

I know you can do this for Win32 as Follows without having to reassign f file handle.

Assignfile(f,fname);
Reset(f,1);
BlockRead(f,jokeA,SizeOf(jokeA));

Reset(f,1);
BlockWrite(f,jokeB,SizeOf(jokeB));
CloseFile(f);
Was it helpful?

Solution

you can:

using lFile := File.Open('c:\jokes.dat', FileMode.ReadWrite) do begin
  var lReader := new BinaryReader(lFile);
  // read using reader

  lFile.Position := lFile.Length;
  var lWriter := new BinaryWriter(lFile);
  lWriter.Write...

end;

OTHER TIPS

FWIW, I don't think you can do that with the Binary* classes. You can use the FileStream class, though. Also, FWIW, the classic Pascal/Delphi Reset(File) command actually opens a new handle - it's only the file variable (essentially the file name) that's reused.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top