我有以下 Dlang 语言代码:

import std.stdio;

void main()
{
    auto file1 = File('example.txt', 'w');
    file1.writeln('Hello, world!');

    auto file2 = File('example.txt', 'r');
    writeln(file2.name()); // 输出 'example.txt'
    writeln(file2.eof()); // 输出 false
    file2.detach();

    writeln(file1.eof()); // 输出 false
    file1.readln(); // 读取 'Hello, world!'
    writeln(file1.eof()); // 输出 true
    file1.close(); // 关闭文件
}

运行报错如下:

example.txt
false
false
std.stdio.StdioException@std/stdio.d(5156): Bad file descriptor
----------------
??:? @safe void std.stdio.StdioException.opCall() [0x44ecf1]
??:? @trusted const(long) std.stdio.readlnImpl(shared(core.stdc.stdio._IO_FILE)*, ref char[], dchar, std.stdio.File.Orientation).__lambda9() [0x442d90]
??:? @safe ulong std.stdio.readlnImpl(shared(core.stdc.stdio._IO_FILE)*, ref char[], dchar, std.stdio.File.Orientation) [0x442cf8]
??:? @safe ulong std.stdio.File.readln!(char).readln(ref char[], dchar) [0x43dd6c]
??:? @safe immutable(char)[] std.stdio.File.readln!(immutable(char)[]).readln(dchar) [0x43dcae]
??:? _Dmain [0x43c97d]

为什么调用 file2.detach();file1.readln 无法读取了呢?我查看了 https://dlang.org/phobos/std_stdio.html 中对 detach 的说明如下:

@trusted void detach();
Detaches from the underlying file. If the sole owner, calls close.
Throws:
ErrnoException on failure if closing the file.

我的理解是 detach()close() 的区别在于,detach() 方法只是将 File 对象与底层文件分离,但不会关闭文件,而 close() 方法会关闭文件,释放资源。难道我的理解有错误,请帮我分析解释。

解释:

在调用 file2.detach(); 后,file2example.txt 文件的关联被分离了,但是 example.txt 文件仍然被 file1 所关联。在调用 file1.readln() 时,它尝试读取 example.txt 文件,但是由于在之前的 file2.detach() 中,example.txt 文件已经与 file2 的关联被分离了,所以此时读取 example.txt 文件的操作会失败,从而导致了 std.stdio.StdioException 异常的抛出。

因此,调用 file2.detach(); 后,需要确保在读写 example.txt 文件时只使用与之关联的 File 对象(即 file2),而不是其他对象(如 file1)。


原文地址: http://www.cveoy.top/t/topic/ox89 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录