Read all the numbers from line of file - freepascal

On the first line of data.txt I have two numbers separated by space.
How do I read / output to the screen each number?
This is my code so far which reads only the first number of the line.
program p1;
uses crt;
const filename = 'data.txt';
var
cv : integer;
myfile: text;
i,sum:integer;
begin
i:=0;
sum:=0;
Assign(myfile, filename);
Reset(myfile);
while not (Eof(myfile)) do
begin
while not eoln(myfile) do begin
Readln(myfile, cv);
Writeln(cv);
end;
end;
close(myfile);
end.
This is my data.xt file :
4 10
250
350
400
1000
I can't get to that 10 on the first line,

Many ways to do it, but the one closest to what you have already is to remove the inner loop and use READ instead of READLN. Like so:
program p1;
uses crt;
const filename = 'data.txt';
var
cv : integer;
myfile: text;
begin
Assign(myfile, filename);
Reset(myfile);
while not (Eof(myfile)) do begin
Read(myfile, cv);
Writeln(cv);
end;
close(myfile);
end.

Related

DSiWin32.DSiGetHtmlFormatFromClipboard not working?

I am trying to use the DSiGetHtmlFormatFromClipboard function from the well known DSiWin32 library.
Edit: There is a much newer version of DSIWin32.pas 1.94 from 2016-10-19 which is contained in the current version of OmniThreadLibrary_3.07.1. The one I've linked to in the first line of my question is much older: 1.66 from 2012-04-20. However, also in this newer version of DSIWin32.pas the function DSiGetHtmlFormatFromClipboard does not work although I've made sure that no other clipboard programs are running.
So I put some text on the clipboard which includes the HTML format e.g. by copying some text from Chrome web-browser.
And then I use this code to get the HTML format from the clipboard:
if DSiWin32.DSiIsHtmlFormatOnClipboard then
begin
CodeSite.Send('HTML-Format string:', DSiWin32.DSiGetHtmlFormatFromClipboard);
end;
While the DSiIsHtmlFormatOnClipboard function does work (it gives back True if there is HTML Format on the clipboard and gives back False if there is no HTML Format on the clipboard), the DSiGetHtmlFormatFromClipboard function always gives back an empty string although there is HTML Format in the clipboard:
So I debugged function DSiGetHtmlFormatFromClipboard: string; in DSiWin32.pas:
On this line:
hClipData := GetClipboardData(GCF_HTML);
hClipData is always 0, so the following code is not executed.
GetClipboardData is a function from Winapi.Windows and according to MSDN documentation:
Retrieves data from the clipboard in a specified format. The clipboard
must have been opened previously.
Which is the case in the DSiWin32 code.
So why does the DSiGetHtmlFormatFromClipboard always give back an empty string?
OS: Windows 7 x64
GetLastError retrieved immediately after the line hClipData := GetClipboardData(GCF_HTML);:
ERROR_CLIPBOARD_NOT_OPEN 1418 (0x58A) Thread does not have a
clipboard open.
This is strange because the preceding line is: Win32Check(OpenClipboard(0)); and it does not fail.
Here is the relevant parts of the MCVE:
var
GCF_HTML: UINT;
function DSiIsHtmlFormatOnClipboard: boolean;
begin
Result := IsClipboardFormatAvailable(GCF_HTML);
end; { DSiIsHtmlFormatOnClipboard }
function DSiGetHtmlFormatFromClipboard: string;
var
hClipData : THandle;
idxEndFragment : integer;
idxStartFragment: integer;
pClipData : PChar;
begin
Result := '';
if DSiIsHtmlFormatOnClipboard then
begin
Win32Check(OpenClipboard(0));
try
hClipData := GetClipboardData(GCF_HTML);
if hClipData = 0 then
RaiseLastOSError;
pClipData := GlobalLock(hClipData);
Win32Check(assigned(pClipData));
try
idxStartFragment := Pos('<!--StartFragment-->', pClipData); // len = 20
idxEndFragment := Pos('<!--EndFragment-->', pClipData);
if (idxStartFragment >= 0) and (idxEndFragment >= idxStartFragment) then
Result := Copy(pClipData, idxStartFragment + 20, idxEndFragment - idxStartFragment - 20);
finally GlobalUnlock(hClipData); end;
finally Win32Check(CloseClipboard); end;
end;
end; { DSiGetHtmlFormatFromClipboard }
procedure TForm1.Button1Click(Sender: TObject);
begin
if DSiIsHtmlFormatOnClipboard then
ShowMessage(DSiGetHtmlFormatFromClipboard)
else
ShowMessage('No HTML Format on Clipboard');
end;
initialization
GCF_HTML := RegisterClipboardFormat('HTML Format');
end.

Lazarus insert sql results int string grid

I have problem inserting sql results into TStringGrid.I have following code:
var i:Integer;
begin
SqlQuery1.SQL.Text:= 'SELECT * FROM `users`';
SqlQuery1.Open;
MySql55Connection1.Open;
i:= 0;
while not SQLQUERY1.EOF do
begin
i:= i+1;
StringGrid1.Cells[0,i]:= SqlQuery1.FieldByName('Username').AsString;
StringGrid1.Cells[1,i]:= SqlQuery1.FieldByName('Password').AsString;
StringGrid1.Cells[2,i]:= SqlQuery1.FieldByName('id').AsString;
end;
end;
So in my database only one line. But program adding a lot of copies of this line in StringGrid and it causes error(Index out of bounds).
Danger
It appears you are storing passwords in plain text form in a database.
This is an extremely bad idea.
Never store passwords in a database.
Use salted hashes instead.
See: How do I hash a string with Delphi?
There are a couple of other problems in your code:
You don't ensure that the stringgrid has enough rows to hold your data.
You're not moving to the next line in the query.
You're opening the query before the connection is open.
You're using FieldByName inside a loop, this is going to be very slow.
Simple solution
Use a DBGrid.
If you insist on using a StringGrid
I suggest refactoring the code like so:
var
i,a:Integer;
FUsername, FPasswordHash, Fid, FSalt: TField;
begin
if not(MySQl55Connection.Active) then MySql55Connection1.Open;
SqlQuery1.SQL.Text:= 'SELECT * FROM users'; //only use backticks on reserved words.
SqlQuery1.Open;
FUsername:= SqlQuery1.FieldByName('Username');
//do not use plain text passwords!!
FPasswordHash:= SQLQuery1.FieldByName('SaltedPasswordHashUsingSHA256');
FId:= SqlQuery1.FieldByName('id');
FSalt:= SQLQuery1.FieldByName('SaltUsingCryptoRandomFunction');
a:= StringGrid1.FixedRowCount;
if SQLQuery1.RecordCount = -1 then StringGrid1.RowCount = 100 //set it to something reasonable.
else StringGrid1.RowCount:= a + SQLQuery1.RecordCount;
//SQLQuery1.DisableControls
try
i:= StringGrid1.FixedRowCount;
while not(SQLQuery1.EOF) do begin
if i >= StringGrid1.RowCount then StringGrid1.RowCount:= i;
StringGrid1.Cells[0,i]:= FUserName.AsString;
StringGrid1.Cells[1,i]:= FPasswordHash.AsString;
StringGrid1,Cells[3,i]:= FSaltInHex.AsString;
StringGrid1.Cells[2,i]:= FId.AsString;
SQLQuery1.Next; //get next row.
Inc(i);
end; {while}
finally
//just in case you want to do endupdate or close the SQLQuery or do SQLQuery1.EnableControls
end;
end;
Basic security example
Here's how to hash a password:
Download Lockbox3.
Put a THash on your form and set the hash property to SHA-512.
Use the following code to produce a hash result.
function StringToHex(const input: string): AnsiString;
var
NumBytes, i: Integer;
B: Byte;
W: word;
Wa: array[0..1] of byte absolute W;
begin
NumBytes := input.length * SizeOf(Char);
SetLength(Result, NumBytes * 2);
for i := 1 to NumBytes do begin
if SizeOf(Char) = 1 then begin
B:= Byte(input[i]);
BinToHex(#B, #Result[(I*2)+1], 1);
end else begin
W:= Word(input[i]);
BinToHex(#Wa[0], #Result[(i*4+0)],1);
BinToHex(#Wa[1], #Result[(i*4+1)],1);
end; {else}
end;
end;
function TForm1.HashPassword(var Password: string; const Salt: string): string;
var
KillPassword: pbyte;
begin
Hash1.HashString(StringToHex(Password)+StringToHex(Salt));
KillPassword:= PByte(#Password[1]);
FillChar(KillPassword^, Length(Password)*SizeOf(Char), #0); //remove password from memory.
Password:= ''; //Now free password.
end;
function GenerateSalt( ByteCount: integer = 32): string;
var
Buffer: TMemoryStream;
begin
Buffer := TMemoryStream.Create;
try
Buffer.Size := ByteCount;
RandomFillStream( Buffer);
result := Stream_to_Base64( Buffer);
finally
Buffer.Free
end;
end;
This is the minimum amount of work you can get away with whilst still having things secure.
Do not think that your passwords are unimportant because you just have a toy database, because people reuse passwords and thus your toy passwords end up being the same passwords used for online banking and such.
People are lazy....

How can I declare a function from within a function in Delphi/FreePascal without nesting them?

I would like to do something like this:
(I want to conserve the functions public so I can access them from other procedures/functions).
The functions are on the same form (frmSequenciador) - I didn't post it for it is huge in its integrity..
function geradorDeVetores():TIntArray;
var
contador: Integer;
vetor: array [1..numMax] of integer;
begin
Randomize;
for contador:=1 to numMax do
begin
if contador = 1 then
vetor[contador]=float_round_down(Random*10);
else vetor[contador]:= ***frmSequenciador.evitaRepeticao(contador, vetor)***;
end;
end;
function evitaRepeticao(pos: integer; vetor:TIntArray):integer;
var
numigual: boolean;
temporario, cont: integer;
begin
numigual:=true;
temporario:= float_round_down(Random*10);
for cont:=1 to pos-1 do
if temporario <> vetor[cont] numigual:=false else numigual:=true;
if numigual=false then evitaRepeticao():=temporario else evitaRepeticao():=***frmSequenciador.evitaRepeticao(pos, vetor)***;
end;
It was a simple matter of removing the frmSequenciador prefix of the functions as Ken White stated.
What I wanted to know is: if two functions are inside the same form unit (thx Jerry), do we need a prefix to call each other?
It seems not. Thanks all!

Calling TEdit objects based on DB query

I have a form with 7 TEdit having name EditPhone1, EditPhone2 and so on.
In the same form I query a DB to get data to fill those TEdits. Of course I cannot know in advance how many results the query will return.
How can I call the various TEdit objects when looping on the rowcount of the query?
Use FindComponent to "convert" a component name to the component itself:
var
Edit: TEdit;
I: Integer;
begin
DataSet.First;
I := 1;
while not DataSet.Eof do
begin
Edit := TEdit(FindComponent(Format('EditPhone%d', [I])));
if Edit <> nil then
Edit.Text := DataSet.FieldValues['PhoneNo'];
DataSet.Next;
Inc(I);
end;
Now, this requires to hard-code the EditPhone%d string into the source which results in all kinds of maintainability issues. For example: consider renaming the edits.
Alternative 1:
To not rely on the component names, you could instead make use of TLama's idea and add all the edits to a list:
uses
... , Generics.Collections;
type
TForm1 = class(TForm)
EditPhone1: TEdit;
...
procedure FormCreate(Sender: TObject);
procedure FormDestroy(Sender: TObject);
private
FEdits: TList<TEdit>;
end;
procedure TForm1.FormCreate(Sender: TObject);
begin
FEdits := TList<TEdit>.Create;
FEdits.AddRange([EditPhone1, EditPhone2, EditPhone3, EditPhone4, EditPhone5,
EditPhone6, EditPhone7]);
end;
procedure TForm1.FormDestroy(Sender: TObject);
begin
FEdits.Free;
end;
procedure TForm1.ADOQuery1AfterOpen(DataSet: TDataSet);
var
I: Integer;
begin
DataSet.First;
I := 0;
while (not DataSet.Eof) and (I < FEdits.Count) do
begin
FEdits[I].Text := DataSet.FieldValues['PhoneNo'];
DataSet.Next;
Inc(I);
end;
end;
This still requires some maintenance in case of adding edits in future.
Alternative 2:
You could also loop over all edits in the form to find the ones tagged to be added to the list, instead of adding them each explicitly:
procedure TForm1.FormCreate(Sender: TObject);
var
I: Integer;
begin
FEdits := TList<TEdit>.Create;
for I := 0 to ComponentCount - 1 do
if (Components[I] is TEdit) and (TEdit(Components[I]).Tag = 1) then
FEdits.Add(TEdit(Components[I]));
end;
But keeping those tags up to date is another burden.
Alternative 3:
I suggest you use a TDBGrid which is a data-component. Opening the linked dataset will automatically add all phone numbers to the grid. With some settings, the grid may kind of look like a couple of edits below each other.
You can, for example, use Tag property, to find needed component. Set all you TEdit's tag from 1 to 7 (or more), and find component by:
Var I: Integer;
MyEdit : TEdit;
For I = 0 To Self.ComponentCount - 1 Do
if (Self.Components[I] IS TEdit) AND (Self.Components[I] AS TEdit).Tag = YourTag
MyEdit = (Self.Components[I] AS TEdit);
You can also dynamically create so many TEdits, you need, and assign Tag property on creation, and find it this code later in runtime.
I'd suggest using DBCtrlGrid. You place your controls for one row on it, and it repeats the controls for as many rows as your data set has.
Get query result (usually using .RowCount property of TDataset return)
After getting the number of row, do iteration to make TEdit and set the text property
Here is sample of code:
...
For i:=0 to RowCount do
Begin
A:=TEdit.Create(self);
A.Parent:=AForm;
A.Top:=i*14;
A.Text:=ADataset.Field(i).AsString;
End;
...

Pascal - not writing to file

Howdy, Pascal masters!
I've got a file type of custom records:
DBCell = record
Name: string[10];
Surname: string[15];
Balance:integer;
OpenDate: record
year: integer;
month: 1..12;
day:1..31
end;
AccountN: string[10];
end;
DBFile = file of DBCell;
And functions, that open and add new element to file:
procedure Fopenf(var F:DBFile; var FName:string; var FOpened:boolean);
begin
Assign(F,FName);
rewrite(F);
FOpened:=true;
end;
procedure InsN(var F:DBFile;var cell:DBCell;var FOpened:boolean);
begin
Write(F,cell);
Close(F);
Rewrite(F);
Writeln('Added');
FOpened:=false;
end;
Problem is, nothing is actually written to file. What am I doing wrong?
It's been a long time since I've done any Pascal, but IIRC Rewrite truncates the file. You should use Append.
You don't need the Rewrite() after inserting a record in the file:
procedure InsN(var F:DBFile;var cell:DBCell;var FOpened:boolean);
begin
Write(F,cell);
Close(F);
Writeln('Added');
FOpened:=false;
end;
If you don't want to truncate the file every time you open it:
procedure Fopenf(var F:DBFile; var FName:string; var FOpened:boolean);
begin
Assign(F,FName);
append(F);
FOpened:=true;
end;
The problem is the 'rewrite' call in InsN. 'Rewrite' creates a new file, so by calling it at the end of your program, you are creating a new, empty file!