file - 包含 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() 的影响?
解决方案
推荐阅读
- android - 新版库与 jcenter 不同步
- android - com.google.gson.JsonSyntaxException:java.lang.IllegalStateException:应为 BEGIN_ARRAY,但在第 1 行第 101 列路径为 BEGIN_OBJECT
- angular - 如何在angular 6中使用three.js的扩展库(如OBJLoader、SceneUtils...)?
- javascript - 如何在jmeter的负载测试中捕获文件的下载时间
- c++ - 如何使用地图容器?
- react-native - 无法识别的字体系列“entypo”
- corda - 在corda的H2控制台中找不到空指针异常和表“SYNONYMS”错误
- java - 如何从Java中非常长的文本文件中删除以特定字符开头和结尾的行?
- sql - 如何在 SQL Server 的非标识列中查找间隙序列
- c# - Xamarin 表单蓝牙键盘输入输入缓慢