【问题标题】:Writing/reading a file in binary mode in Clisp在 Clipp 中以二进制模式写入/读取文件
【发布时间】:2013-11-29 06:30:31
【问题描述】:

我正在编写这个程序,它应该从文件中读取,对内容进行一些处理,然后写入保留原始行结尾的输出文件。如果文件有CRLF 结尾,输出文件也应该有。我的问题是写行结尾,尤其是CLISP 实现(它适用于gcl)。当我尝试编写换行符(LF)时,文件最终以CRLF 结尾。我猜这与CLISP 的实现有关。
我需要一种write the file in binary mode 的方法,就像其他语言一样。规范中的标准 I/O 函数仅采用可选的流名称和要写入的内容。

您可以通过以下方式重现该行为:

(with-open-file (out-file "test.dat" :direction :output)
  (setf ending #\linefeed)
  (princ "First Line" out-file)
  (write-char ending out-file)
  (princ "Second Line" out-file)
  (write-char ending out-file)
  (princ "Second Line" out-file))

我需要一个适用于 Windows 的解决方案。

【问题讨论】:

    标签: file-io lisp common-lisp clisp line-endings


    【解决方案1】:

    您需要指定:EXTERNAL-FORMAT 参数,提及line terminator mode

    (with-open-file (out-file "test.dat" :direction :output :external-format :unix)
      ...)
    

    Windows 上的外部格式默认为:dos,因为这是 Microsoft 系统上的标准。

    请注意,如果您实际上是在编写文本,您确实需要二进制模式。在 Common Lisp(相对于 C 和 Emacs Lisp)中,binary i/o(读取和写入 bytes)和文本 i/o(到达和写入 characters)之间有非常明显的区别,就像number 不是字符,反之亦然,即使字符具有整数 code

    【讨论】:

    • 为什么在这种情况下以二进制模式读取会更慢?而且,无法维护怎么办?
    • 因为您正在手动重新实现系统功能。如果您想这样做,请使用程序集:-)
    • 呵呵。我更喜欢这种方法;它更简单。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-09-30
    相关资源
    最近更新 更多