首页 > 解决方案 > 包含 BlockRead() 的函数无法访问“结果”变量

问题描述

我想创建一个将文件内容保存到字符串中的函数。我为此使用了 BlockRead() ,但它给了我一个非常奇怪的行为。

我创建了以下 fileToString() 函数,它实际上只从文件中读取一个字节,然后尝试返回一个常量 'foo' 字符串作为结果。这一切都始于 Button1Click 功能和一个很好的选择文件对话框。

unit Unit1;

interface

uses
  Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics,
  Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls;

type
  TForm1 = class(TForm)
    Button1: TButton;
    procedure Button1Click(Sender: TObject);

    private
      selectedFile: string;
      FileIntoString: string;
  end;

var
  Form1: TForm1;

implementation
{$R *.dfm}

procedure TForm1.Button1Click(Sender: TObject);
  function fileToString(fileName: String): String;
  var
      aFile   : File;
      oneByte : byte;
  begin
    Result := '';

    if fileName <> '' then begin

      AssignFile(aFile, fileName);
      Reset(aFile);

      BlockRead(aFile, oneByte, 1);    //Brakpoint 1
      Result := 'foo';                 //Brakpoint 2

      Reset(aFile);
      CloseFile(aFile);
    end;
  end;

var
  dlg: TOpenDialog;
begin
//CHOOSE FILE
  selectedFile := '';
  dlg := TOpenDialog.Create(nil);
  try
    dlg.InitialDir := '.\';
    dlg.Filter := 'All files (*.*)|*.*';
    if dlg.Execute(Handle) then
      selectedFile := dlg.FileName;
  finally
    dlg.Free;
  end;

  FileIntoString := fileToString(selectedFile);
end;
end.

当我执行该操作时,我收到一条错误消息“0xfe317469 处的访问冲突:读取地址 0xfe317465”并且应用程序崩溃。

当我在断点 1 中暂停程序时,在执行之前BlockRead(),局部变量 'Result' 的值为 ' ' [空字符串,在函数的请求中分配] 并且局部变量 'fileName' 的值是文件路径的字符串.

在断点 2 中执行BlockRead()和暂停后,我得到局部变量“Result”和“fileName”的“Inaccesible value”,并且在执行该Result := 'foo';行后我得到了访问冲突。

为什么我的局部变量会受到 BlockRead() 的影响?

标签: filedelphifile-read

解决方案


推荐阅读