Recent

Author Topic: COPY Problem  (Read 2579 times)

Andy Anderson

  • New member
  • *
  • Posts: 6
COPY Problem
« on: August 07, 2014, 05:15:41 pm »

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

  • Hero Member
  • *****
  • Posts: 2513
Re: COPY Problem
« Reply #1 on: August 07, 2014, 06:01:43 pm »
Welcome to FPC/Lazarus.

After calling:
Code: [Select]
  SETLENGTH(REC, 3100);
REC points at a valid memory location that is fit for 3100 characters.

After calling:
Code: [Select]
  FLERES := FILEREAD(FLE1A, REC, SIZEOF(REC));
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: [Select]
  FLERES := FILEREAD(FLE1A, REC[1], SIZEOF(REC));

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: [Select]
  FLERES := FILEREAD(FLE1A, REC[1], Length(REC));
« Last Edit: August 07, 2014, 06:03:17 pm by engkin »

Andy Anderson

  • New member
  • *
  • Posts: 6
Re: COPY Problem
« Reply #2 on: August 09, 2014, 11:06:20 pm »
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.
 

 

TinyPortal © 2005-2018