FreePascal - How can I copy a file from one location and paste it in another? [closed] - pascal

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 2 years ago.
Improve this question
I am attempting to get a program to paste a copy of itself in the windows start-up folder. I have only been able to find the Lazarus function included in FileUtils, CopyFile() but as I'm not using Lazarus this solution doesn't work for me. is there any other way that I can do this in FreePascal? all other things related to files that I can find for FreePascal are referring to text files or the File type.

You may copy one file to another with the oldschool File type and routines:
function CopyFile(const SrcFileName, DstFileName: AnsiString): Boolean;
var
Src, Dst: File;
Buf: array of Byte;
ReadBytes: Int64;
begin
Assign(Src, SrcFileName);
{$PUSH}{$I-}
Reset(Src, 1);
{$POP}
if IOResult <> 0 then
Exit(False);
Assign(Dst, DstFileName);
{$PUSH}{$I-}
Rewrite(Dst, 1);
{$POP}
if IOResult <> 0 then begin
Close(Src);
Exit(False);
end;
SetLength(Buf, 64 * 1024 * 1024);
while not Eof(Src) do begin
{$PUSH}{$I-}
BlockRead(Src, Buf[0], Length(Buf), ReadBytes);
{$POP}
if IOResult <> 0 then begin
Close(Src);
Close(Dst);
Exit(False);
end;
{$PUSH}{$I-}
BlockWrite(Dst, Buf[0], ReadBytes);
{$POP}
if IOResult <> 0 then begin
Close(Src);
Close(Dst);
Exit(False);
end;
end;
Close(Src);
Close(Dst);
Exit(True);
end;
begin
if not CopyFile('a.txt', 'b.txt') then
Halt(1);
end.

Related

How do you call a procedure given the procedure pointer in Pascal? [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 8 days ago.
This post was edited and submitted for review 8 days ago and failed to reopen the post:
Original close reason(s) were not resolved
Improve this question
Given an array of pointers where those pointers are to procedures and where they pass a single pointer passed to a procedure, how do you call the passed pointer?
procedure CallPointerProc(Proc : Pointer);
begin
// ???????????
end;
The old DOS method was fairly simple but inline is not available on Windows port so couldn't even convert to ebx,esp, etc..:
inline(
$89/$E3/ {mov bx,sp}
$36/$FF/$1F/ {call dword ptr ss:[bx]}
$83/$C4/$04); {add sp,4}
In general, you should not pass a blank pointer but a type that describes the exact type of subroutine like parameters with their types and return type in case of a function.
Example on how to declares procedure or function types
type
// A procedure with no parameters
TProc = procedure;
// A procedure that expexcts a string
TStringProc = procedure(str: string);
// A function that expects and returns a string
TStringToStringFunc = function(str: string): string;
A function that expects a pointer to a procedure and calls it:
procedure CallPointerProc(Proc : TProc);
begin
Proc();
end;
A function that expects a blank pointer, casts it to a procedure and then calls that:
procedure CallPointerProc(Proc : Pointer);
var
TypedProc: TProc;
begin
TypedProc := TProc(Proc);
TypedProc();
end;
Demo code that works with both definitions of CallPointerProc above. Note that we use the # symbol to get the address of a defined procedure or function.
procedure Demo;
begin
Writeln('Hello World');
end;
begin
CallPointerProc(#Demo);
Readln;
end.

Error : can't use the wintypes and winprocs [duplicate]

This question already has an answer here:
What are WinTypes, WinProcs and SW_NORMAL?
(1 answer)
Closed 4 years ago.
i can't execute my program in lazarus does the lazarus support the wintypes and winprocs
base.pas (2,13) Fatal: Can not find WinTypes used by eg the Project Inspector.
program ex;
uses Wincrt,WinTypes, WinProcs;
var
ch:string;
procedure exe (che:string);
begin
writeln('ecrire ch');
readln(che);
if ch ='oui' then
begin
WinExec('cmd /k "C:\TPW\exercice\project\site.html"', SW_NORMAL);
end;
end;
begin
exe(ch);
end.
WinExec function is obsolete. Use ShellExecute instead
program ex;
uses
Windows, // for constant SW_NORMAL
ShellApi; // for function ShellExecute
procedure exe;
var
che: string;
begin
writeln('ecrire ch');
readln(che);
if ch ='oui' then
begin
ShellExecute(0, 'open', 'C:\TPW\exercice\project\site.html', nil, nil, SW_NORMAL);
end;
end;
begin
exe;
end.

Can not create TStream in Lazarus [duplicate]

This question already has answers here:
Delphi: Access Violation at the end of Create() constructor
(2 answers)
Closed 5 years ago.
It fails in this simple example to:
procedure TForm1.Button1Click(Sender: TObject);
var
ts: TStream;
begin
ts.Create; //<---- fails here
ts.Free;
end;
With error:
Project project1 raised exception class 'External: SIGSEGV'.
At address 10000DB38
You are using the wrong code. It should be
procedure TForm1.Button1Click(Sender: TObject);
var
ts: TStream;
begin
ts := TStream.Create; // If Lazarus supports creation of Stream instances.
ts.Free;
end;
Until it is created, your variable ts simply contains junk from previous use of the stack. You have to call the class's constructor to allocate the actual object on the heap and point your ts variable at it.
If Lazarus complains that it can't create an instance of TStream (it may treat it as an abstract class and I don't have Lazarus on this machine to check), try something like this instead:
var
ts: TMemoryStream;
begin
ts := TMemoryStream.Create;
ts.Free;
end;
Instead of TMemoryStream, you could use any other concrete TStream-descendant class.
Was originaly trying this code:
memStream.Create;
But it should be:
memStream := TMemoryStream.Create;
Blah...

It's some kind of magic... or bug? [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 7 years ago.
Improve this question
I added my program to the SendTo. I send two files to it.
They are:
C:\ThisIsMySuperTestHelloWorld\ThisBookIsRedMyPenIsWhite\test.jpg
C:\ThisIsMySuperTestHelloWorld\ThisBookIsRedMyPenIsWhite\hello.jpg
The code below shows C:\ThisIsMySuperTestHelloWorld\ThisBookIsRedMyPenIsWhite\test.jpg#C:\ThisIsMySuperTestHelloWorld\ThisBookIsRedMyPenIsWhite\test.jpg
procedure TForm1.FormCreate(Sender: TObject);
var Files: array of PAnsiChar;
i: Integer;
begin
SetLength(Files, 2);
for i:=0 to 1 do begin
Files[i] := PAnsiChar(ParamStr(2+i));
end;
ShowMessage( Files[0] +'#' + Files[1] );
end;
I use Delphi 6 on Windows7.
Under Delphi Xe3 (still Win7) I changed (both) PAnsiChar to PWideChar and I have the same effect.
My SendTo link links to:
"C:\<PATH_HERE>\Project1.exe" c
and is placed here:
C:\Users\<USER>\AppData\Roaming\Microsoft\Windows\SendTo
What about using strings? For example:
procedure HandleParams;
var Files: array of string;
i: Integer;
begin
SetLength(Files, ParamCount);
for i := 1 to ParamCount do
Files[i-1] := ParamStr(i);
if ParamCount >= 2 then
ShowMessage( Files[0] +'#' + Files[1] );
end;
Your code does not work, because PAnsiChar is only a Pointer and does not store the actual string data. When you assign the string returned from the ParamStr function only a pointer to the (temporary) function result is stored. The actual data is overwritten with the next function call. This can even crash your program when further used.
By the way, your ParamStr index iterates over 2 and 3, with references to the second and third parameter; maybe that's not intended as the arguments start at index 1 (index 0 being the program call itself)?
To solve the issue one has to store the string data, which makes the pointers kinda useless, but anyway, here's a fixed version of your example:
procedure HandleParamsPAnsi;
var Files: array of PAnsiChar;
FilesData: array of AnsiString;
i: Integer;
begin
SetLength(Files, 2);
SetLength(FilesData, 2);
for i:=0 to 1 do begin
FilesData[i] := AnsiString(ParamStr(1+i));
Files[i] := PAnsiChar(FilesData[i]);
end;
ShowMessage( Files[0] + '#' + Files[1] );
end;

Brute Force Algorithm to solve the TSP in Delphi [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 9 years ago.
Improve this question
I'm writing a program for an extended project to simulate the travelling salesman problem. So far I have written it to allow the user to enter a route, as well as 'solving' a route using a nearest neighbour algorithm. I am now trying to write a brute force algorithm to solve for a selection of cities, from 3 cities up to about 13/14. The program is for the purpose of showing how the increase in number of cities leads to an exponential/factorial increase in the time taken to calculate the shortest route. I have tried to write a recursive function but cannot get my head around how it would work. I am in desperate need of some guidance as to how to do this. Any help would be appreciated.
Since there is no tag with Delphi version, then any version suits the TopicStarter just fine. I would base thus draft on XE2 version then. I also would assume that each town is only visited once. I would assume that there is a road network rather than a private airplane, that is between any chosen cities A and B there may be direct path or may not (connection only through other cities).
type TCity = class
public
Name : string;
Routes : TList<TCity>; // available roads to/from this place
LeftFor : integer; // where did the merchant went next; -1 if did not arrived or left, used to iterate all the paths
CameFrom: TCity; // nil initially
.....
End; // writing this draft from phone ( testing official StackOverflow Android app) would not write boilerplate with creating/free in internal objects - do it yourself
Type TPath = TArray<TCity>; // for your app you would add segments and total cost and whatever
Var World: TArray<TCity >; // fill cities and links yourself
AllPaths: TList<TPath>; // create yourself
Current: TList<TCity >; // create yourself
Procedure SaveResult;
Begin AllPaths.Add( Current.ToArray) end;
Function TryNextCity: boolean;
Var c1,c2: TCity; I : integer;
Begin
c1 := Current.Last; // where we are
While true do begin
Inc( c1.LeftFor) ;
If c1.LeftFor >= c1.Routes.Count // tried all ways?
Then Exit( false );
c2 := c1.Routes (. c1.LeftFor .);
if c2 = c1.CameFrom then continue;
if c2.LeftFor >= 0 then continue; // already were there
AddCity(c2);
Exit( True) ;
End;
End;
Procedure AddCity( const City: TCity) ;
Begin
Assert ( not Current.Contains( City) ) ;
If Current.Count = 0
then City.CameFrom := nil //starting point
else City.CameFrom := Current.Last;
City.LeftFor := -1;
Current.Add(City) ;
End;
Procedure Withdraw;
Begin
Assert ( Current.Count > 0);
With Current.Last do begin
CameFrom := nil;
LeftFor := -1;
End;
Current.Delete( Current.Count - 1) ;
End;
Procedure Recurs;
Var DeadEnd : boolean;
Begin
DeadEnd := true;
while TryNextCity() do begin
DeadEnd := false;
Recurs();
end;
if DeadEnd then SaveResult();
Withdraw ();
End;
Procedure RunBruteForce;
Var c: TCity ;
Begin
AllPaths.Clear;
For c in world do begin
Current.Clear;
AddCity( c );
Recurs();
End;
End;
PS. #MartynA looks like I cannot comment my answer now in Android. So my reply is: this questions as is now falls into a triangle between "do my homework", "write a textbook or at least an essay" and "throw a bunch of vague nice ideas, correct per se, but none of which would be detailed and complete enough to be called an answer".
I only started the answer to try new SO app, and only go on for it does not have options to delete the answer.

Resources