Forum > Beginners
COPY Problem
(1/1)
Andy Anderson:
Am new to Pascal but not programming. Naturally, I'm tending
to misinterpret statements in the manuals. The below code
compiles okay but bombs on the COPY statement with an access
violation error. Is the problem my use of ansistrings ?
The OS is Windows XP.
A pointer would be appreciated.
Thanks in advance.
program HELLO4;
Uses sysutils;
VAR REC : ANSISTRING;
VAR FLE1A, FLERES : LONGINT; PART : ANSISTRING;
BEGIN
SETLENGTH(REC, 3100);
FLE1A := FileOpen ('C:\THREEWIN\UPDPAT01.WIN',fmOpenRead);
{Semicolons after BEGIN and END done for consistency.}
IF FLE1A < 0 THEN BEGIN; WRITELN ('Open failed.'); exit; END;
FLERES := FILESEEK(FLE1A, 0, fsFromBeginning);
IF FLERES < 0 THEN BEGIN; WRITELN ('Seek failed.'); exit; END;
FLERES := FILEREAD(FLE1A, REC, SIZEOF(REC));
IF FLERES < 0 THEN BEGIN; WRITELN ('Read failed.'); exit; END;
FILECLOSE (FLE1A);
WRITELN ('Trying copy');
PART := COPY(REC, 200, 80);
WRITELN ('Copy sucess');
WRITELN (PART);
END.
engkin:
Welcome to FPC/Lazarus.
After calling:
--- Code: --- SETLENGTH(REC, 3100);
--- End code ---
REC points at a valid memory location that is fit for 3100 characters.
After calling:
--- Code: --- FLERES := FILEREAD(FLE1A, REC, SIZEOF(REC));
--- End code ---
REC points at some address based on the contents of the file C:\THREEWIN\UPDPAT01.WIN.
You were supposed to pass the address of the first char REC[1], not the address of REC:
--- Code: --- FLERES := FILEREAD(FLE1A, REC[1], SIZEOF(REC));
--- End code ---
There is another mistake, SIZEOF(REC) is 4 bytes on 32bit OS and 8 bytes on 64bit OS. I believe your intention was to read as much as REC would fit:
--- Code: --- FLERES := FILEREAD(FLE1A, REC[1], Length(REC));
--- End code ---
Andy Anderson:
Thanks, Engkin. It works fine now.
This is how I intend to handle random files.
If you know of a more appropriate way to
read/write, I'd be interested in knowing.
Navigation
[0] Message Index