Link to home
Start Free TrialLog in
Avatar of T0masz
T0masz

asked on

write a array of char to file

I have a TBuf as array of char and I want to write it to a file without loosing any data(if i write it as string i loose some of the data)

Does anyone know which function to use or how to do it.

Tom
Avatar of StevenB
StevenB

You'll probably want to use the TFileStream object, specifically the WriteBuffer method. I'll write you an example when I get a spare minute :o)
ASKER CERTIFIED SOLUTION
Avatar of TheRealLoki
TheRealLoki
Flag of New Zealand image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Something along these lines should do the trick:


const
  aCharArray : array[1..10] of Char = ('a','b','c','d','e','f','g','h','i','j');
var
  aFileStream : TFileStream;
  aCharArrayLength : Integer;
begin
  aFileStream := TFileStream.Create('C:\Temp\TempFile.dat', fmCreate);
  try
    aCharArrayLength := SizeOf(aCharArray);
    aFileStream.WriteBuffer(aCharArray, aCharArrayLength);
  finally
    FreeAndNil(aFileStream);
  end;
end;
Sorry, didn't refresh, missed that example.
If you use a PChar you would have to say:

fs.Write(mypchar^, buffersize);

John.
I'd use untyped file to write.

var
  f : file;
  buff : array of char;
begin
assignfile(f, 'file.txt');
rewrite(f, 1);
blockwrite(f, buff[0], length(buff));
closefile(f);
end;
Avatar of T0masz

ASKER

I want to be able to use type TBuf as array of char...
Avatar of T0masz

ASKER

function fread2(var SomeFile: File; n : integer) : TBuf; //declared as TBuf = array of char; in the interface section
var nread : integer;
begin
  try
    SetLength(result, n);
    Reset(SomeFile, 1);
    BlockRead(SomeFile, result, n, nread);
    CloseFile(SomeFile);
    //    raise exception.Create('Could not read requested number of bytes.'#13'-Only '+IntToStr(nRead)+' bytes were read');
    Setlength(result, nRead);
  except on e: exception do
    raise exception.Create('Error reading from file:'#13+e.Message);
  end;
end;
Avatar of T0masz

ASKER

buff := fread2(f, strtoint(ar['TiffPage1_image_size'])); // buff as type TBuf as array of char..
assignfile(f, 'c:\test2.tif');
rewrite(f, 1);
blockwrite(f, buff[0], length(buff));
closefile(f);

I get access violation on assignfile
Avatar of T0masz

ASKER

oops fread2(f1,strtoint...... ) but even with that fixed I still get the same error.
BlockRead(SomeFile, result, n, nread);

try to use result[0] instead of result
did you try the filestream method i posted above?
*sigh*