?
Solved

write a array of char to file

Posted on 2005-05-04
13
Medium Priority
?
519 Views
Last Modified: 2010-04-05
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
0
Comment
Question by:T0masz
  • 4
  • 4
  • 2
  • +2
13 Comments
 
LVL 4

Expert Comment

by:StevenB
ID: 13932238
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)
0
 
LVL 17

Accepted Solution

by:
TheRealLoki earned 2000 total points
ID: 13932280
unit Unit1;

interface

uses
  Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs,
  StdCtrls;

const
    maxbuffer = 4096; // bytes

type
  TForm1 = class(TForm)
    OpenDialog1: TOpenDialog;
    SaveDialog1: TSaveDialog;
    bLoad: TButton;
    bSave: TButton;
    procedure bLoadClick(Sender: TObject);
    procedure bSaveClick(Sender: TObject);
  private
    procedure LoadMyBufferFromFile;
    procedure SaveMyBufferToFile;
    { Private declarations }
  public
    { Public declarations }
      buffer: array[1..maxbuffer] of char;
      buffersize: integer; // how many bytes are used in the buffer
// btw, you could use a PChar instead
  end;

var
  Form1: TForm1;

IMPLEMENTATION

{$R *.DFM}

procedure TForm1.LoadMyBufferFromFile;
    var
        fs: TStream;
        total: integer;
        i: integer;
    begin
        if OpenDialog1.Execute then
        begin
            fs := TFileStream.Create(OpenDialog1.Filename, fmOpenRead);
            try
                fs.Read(buffersize, sizeof(buffersize)); // how many bytes are actually saved in the file
                fs.Read(buffer, buffersize); // read the data from the file
// if you were using a pchar you would do fs.Read(mypchar, buffersize);
            finally
                fs.free;
            end;
        end;
    end;

procedure TForm1.SaveMyBufferToFile;
    var
        fs: TStream;
        total: integer;
        i: integer;
    begin
        if SaveDialog1.Execute then
        begin
            fs := TFileStream.Create(SaveDialog1.Filename, fmCreate);
            try
// example only
                buffer[1] := 'H';
                buffer[2] := 'E';
                buffer[3] := 'L';
                buffer[4] := 'L';
                buffer[5] := 'O';
// example only
                buffersize := 5;// set this to the length of the dat ain your buffer
// e.g. buffersize := maxbuffer; if you always want to write the full buffer
               
                fs.Write(buffersize, sizeof(buffersize)); // how many bytes are actually saved in the file
                fs.Write(buffer, buffersize); // write the data from the file
// if you were using a pchar you would do fs.Write(mypchar, buffersize);
            finally
                fs.free;
            end;
        end;
    end;
procedure TForm1.bLoadClick(Sender: TObject);
    begin
        LoadMyBufferFromFile;
    end;

procedure TForm1.bSaveClick(Sender: TObject);
    begin
        SaveMyBufferToFile;
    end;

end.
0
 
LVL 4

Expert Comment

by:StevenB
ID: 13932302
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;
0
Concerto's Cloud Advisory Services

Want to avoid the missteps to gaining all the benefits of the cloud? Learn more about the different assessment options from our Cloud Advisory team.

 
LVL 4

Expert Comment

by:StevenB
ID: 13932308
Sorry, didn't refresh, missed that example.
0
 
LVL 1

Expert Comment

by:jturpin
ID: 13936881
If you use a PChar you would have to say:

fs.Write(mypchar^, buffersize);

John.
0
 
LVL 11

Expert Comment

by:ZhaawZ
ID: 13953577
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;
0
 

Author Comment

by:T0masz
ID: 13964384
I want to be able to use type TBuf as array of char...
0
 

Author Comment

by:T0masz
ID: 13964397
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;
0
 

Author Comment

by:T0masz
ID: 13964469
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
0
 

Author Comment

by:T0masz
ID: 13964477
oops fread2(f1,strtoint...... ) but even with that fixed I still get the same error.
0
 
LVL 11

Expert Comment

by:ZhaawZ
ID: 13966116
BlockRead(SomeFile, result, n, nread);

try to use result[0] instead of result
0
 
LVL 17

Expert Comment

by:TheRealLoki
ID: 13972315
did you try the filestream method i posted above?
0
 
LVL 4

Expert Comment

by:StevenB
ID: 13982832
*sigh*
0

Featured Post

Prep for the ITIL® Foundation Certification Exam

December’s Course of the Month is now available! Enroll to learn ITIL® Foundation best practices for delivering IT services effectively and efficiently.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Objective: - This article will help user in how to convert their numeric value become words. How to use 1. You can copy this code in your Unit as function 2. than you can perform your function by type this code The Code   (CODE) The Im…
In my programming career I have only very rarely run into situations where operator overloading would be of any use in my work.  Normally those situations involved math with either overly large numbers (hundreds of thousands of digits or accuracy re…
Integration Management Part 2
Is your data getting by on basic protection measures? In today’s climate of debilitating malware and ransomware—like WannaCry—that may not be enough. You need to establish more than basics, like a recovery plan that protects both data and endpoints.…
Suggested Courses

840 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question