小编Dex*_*eng的帖子

如何在不耗尽文件描述符的情况下将数千个文件读入内存?

我正在使用以下函数将数千个文件读入内存:

let read_file f =
  let rec f f_channel s =
      try
        let line = input_line f_channel in
        hash_helper f_channel (s^line^"\n")
      with
      | End_of_file -> s
  in
  f (open_in f) ""

Run Code Online (Sandbox Code Playgroud)

但是,一旦文件数量超过一定数量,我的程序就会在运行时崩溃,但出现以下异常:

Fatal error: executable program file not found
Run Code Online (Sandbox Code Playgroud)

谷歌搜索错误会出现以下内容:

https://github.com/ocaml/dune/issues/1633

这似乎与文件描述符耗尽有关。

有没有办法在不耗尽文件描述符的情况下读取所有这些文件?我会假设 Pervasivesinput_line函数会使用某种作业队列来防止程序耗尽和崩溃。

编辑:

我没有意识到你需要关闭in_channel. 这是我的新read_file实现:

let read_file f =
  let rec hash_helper f_channel s =
      try
        let line = input_line f_channel in
        hash_helper f_channel (s^line^"\n")
      with
      | End_of_file ->
        close_in f_channel;
        s …
Run Code Online (Sandbox Code Playgroud)

ocaml

0
推荐指数
1
解决办法
58
查看次数

标签 统计

ocaml ×1