You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Rexx中指定LF或0x0D作为换行符读取文件?

好的,让我来帮你解决这两个Rexx处理特殊换行符的问题:

1. 读取使用LF(0x0A)作为换行符的文件

其实大多数主流的Rexx实现(比如Open Object Rexx、Regina Rexx)的linein()函数已经能自动识别LF作为换行符了。如果你的环境里遇到了无法正确拆分行的异常情况,可以换个思路:先一次性读取整个文件的内容,再手动按LF分割成单独的行。

示例代码如下:

/* 定义目标文件路径 */
target_file = "your_file_path.txt"

/* 打开文件并读取全部内容 */
call stream target_file, "c", "open read"
full_content = charin(target_file, , stream(target_file, "c", "size"))
call stream target_file, "c", "close"

/* 按LF(0x0A)分割内容并处理每一行 */
current_line = ""
do i = 1 to length(full_content)
    current_char = substr(full_content, i, 1)
    if current_char = d2c(0x0A) then do
        if current_line <> "" then do
            say "读取到行:" current_line
            current_line = ""
        end
    end
    else do
        current_line = current_line || current_char
    end
end

/* 处理文件末尾没有LF的最后一行 */
if current_line <> "" then do
    say "读取到最后一行:" current_line
end
2. 让Rexx识别0x0D(CR)作为行分隔符

linein()函数默认只把CRLF(0x0D0A)或者LF当作换行标志,单独的CR不会触发行拆分,所以会把整个文件读成一行。解决的核心是先读取完整文件内容,再手动按CR拆分。这里提供两种实用的方法:

方法一:直接遍历字符拆分

这种方法无需临时文件,直接在内存中处理:

file_path = "your_downloaded_file.txt"

/* 读取完整文件内容 */
call stream file_path, "c", "open read"
content = charin(file_path, , stream(file_path, "c", "size"))
call stream file_path, "c", "close"

/* 按CR(0x0D)拆分并处理每一行 */
line_buffer = ""
do idx = 1 to length(content)
    char = substr(content, idx, 1)
    if char = d2c(0x0D) then do
        if line_buffer <> "" then do
            say "处理行:" line_buffer
            line_buffer = ""
        end
    end
    else do
        line_buffer = line_buffer || char
    end
end

/* 处理最后一行(如果文件末尾没有CR) */
if line_buffer <> "" then do
    say "处理最后一行:" line_buffer
end

方法二:替换CR为LF后用linein()处理

如果你更习惯用linein()的逻辑,可以把CR替换成LF,写入临时文件后再读取:

source_file = "your_source_file.txt"
temp_file = "temp_lf_file.txt"

/* 读取原文件内容 */
call stream source_file, "c", "open read"
content = charin(source_file, , stream(source_file, "c", "size"))
call stream source_file, "c", "close"

/* 将所有CR替换为LF */
converted_content = translate(content, d2c(0x0A), d2c(0x0D))

/* 写入临时文件 */
call stream temp_file, "c", "open write replace"
call charout temp_file, converted_content
call stream temp_file, "c", "close"

/* 用linein()正常读取临时文件 */
do while lines(temp_file) > 0
    line_content = linein(temp_file)
    say "读取到行:" line_content
end

/* 删除临时文件 */
call stream temp_file, "c", "delete"

内容的提问来源于stack exchange,提问作者Sebastia.Net

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.07 07:08:16