两个程序之间使用文件进行通信
我希望用 Pascal 编写的两个单独的程序使用附加文本文件在它们之间进行通信。它对于前 2-3 条消息工作正常,但随后它在 sender.pas 或 receiveer.pas 中给出运行时错误 你知道我的错误在哪里或者你有什么建议吗?
第一个程序receiver.pas
var
f : text;
s : string;
begin
{I-}
Assign(f,'main.in');
while true do
begin
reset(f);
while IOResult<>0 do //
begin // Wait until the file
close(f); // is closed by sender
reset(f); //
end; //
if eof(f) then
close(f)
else
begin
readln(f,s);
close(f);
rewrite(f);
close(f);
writeln(s);
end;
end;
{I+}
end.
第二个程序sender.pas
var
f : text;
s : string;
begin
{I-}
Assign(f,'main.in');
while true do
begin
readln(s);
rewrite(f); //
while IOResult<>0 do //
begin // Wait until the file
close(f); // is closed by receiver
rewrite(f); //
end; //
writeln(f,s);
close(f);
end;
{I+}
end.
I want two separate programs written in Pascal communicate between themselves using additional text file. It works fine for the first 2-3 messages but then it gives run-time error in either sender.pas or receiver.pas Do you know where my mistake is or do you have any suggestion?
First program receiver.pas
var
f : text;
s : string;
begin
{I-}
Assign(f,'main.in');
while true do
begin
reset(f);
while IOResult<>0 do //
begin // Wait until the file
close(f); // is closed by sender
reset(f); //
end; //
if eof(f) then
close(f)
else
begin
readln(f,s);
close(f);
rewrite(f);
close(f);
writeln(s);
end;
end;
{I+}
end.
second program sender.pas
var
f : text;
s : string;
begin
{I-}
Assign(f,'main.in');
while true do
begin
readln(s);
rewrite(f); //
while IOResult<>0 do //
begin // Wait until the file
close(f); // is closed by receiver
rewrite(f); //
end; //
writeln(f,s);
close(f);
end;
{I+}
end.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我注意到的一些事情:
这是什么编译器?德尔福、自由帕斯卡?哪个版本?
我的新(Free Pascal)接收器代码变为:
新的发送器代码是:
Some things I noticed:
What compiler is this? Delphi, Free Pascal? Which version?
My new (Free Pascal) receiver code becomes:
The new sender code is:
有几件事:确保在每次文件操作后检查 IOResult,而不仅仅是重写/重置 - 如果重置/重写失败,不要调用 close - 并且您可能需要在这些重试循环中使用诸如 Sleep(250) 之类的东西。
A couple of things: Make sure you check IOResult after every file operation, not just rewrite/reset - don't call close if your reset/rewrite failed - and you probably want something like a Sleep(250) in those retry loops.