Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reading a txt file into byte values in Delphi

I'm trying to load a .txt file using Delphi and read the byte values of the file in binary. I'm attempting to fetch the txt data as bytes but I'm not sure if it's working because I can't figure out how to display the byte values:

    begin
// open dialog
openDialog := TOpenDialog.Create(self); // Create the open dialog object - assign to our open dialog variable
openDialog.InitialDir := GetCurrentDir;    // Set up the starting directory to be the current one
openDialog.Options := [ofFileMustExist];     // Only allow existing files to be selected
if openDialog.Execute   // Display the open file dialog
then ShowMessage('The file you chose is : '+openDialog.FileName)
else ShowMessage('Open file was cancelled');


// assign file.
fileName:= openDialog.FileName;
AssignFile(myFile, fileName);  //ink a file on a disk to a file variable in our program
Reset(myFile);  //open an existing file or Rewrite to create a new file

// get file length.
fileLength:= FileSize(myFile);


while not Eof (myFile) do
begin

begin
Read(myFile,x);       // read file byte by byte

ShowMessage(x);       //display the data. I'm getting an error here because ShowMessage takes a string value. Tried converting it but I can't find out how to display the binary value of the byte x
.... // [ manipulation code of binary values of bytes goes here. Not sure if this works because I don't know what x is at the moment]
like image 416
HHH Avatar asked Dec 04 '25 07:12

HHH


2 Answers

How about calling

var b:TBytes;
b := TFile.ReadAllBytes('file.txt');

To get the content of a file into an array of bytes?

Just make sure to add ioutils to your uses clause.

like image 104
Wouter van Nifterick Avatar answered Dec 06 '25 21:12

Wouter van Nifterick


Byte is a numeric (integral) type. ShowMessage requires a string. Display a Byte as a string the same way you'd display any other integral type. You can use IntToStr, or Format, or IntToHex, or whatever else you prefer.

You can also just pause your program in the debugger and inspect the variable's value instead of writing special code to make your program display it. The debugger knows about variables' types and how to display them without explicit conversion.

like image 30
Rob Kennedy Avatar answered Dec 06 '25 20:12

Rob Kennedy