在文件中找到特定字节并读取到 Lua 中的特定字节

find specific Byte in File and read until specific byte in Lua

是否可以首先在文件中搜索特定字节后的位置并从文件中读取直到该特定字节的字节?

目前我只能读取一些字节或整个文件,然后搜索该特定字节。 像这样:

local function read_file(path)
  local file = open(path, "r") -- r read mode and b binary mode
  if not file then return nil end
  local content = file:read(64) -- reading 64 bytes
  file:close()
  return content
end

local fileContent = read_file("../test/l_0.dat");
print(fileContent)

function parse(line)
   if line then
     len = 1
     a = line:find("V", len +1) --find V in content 
     return a
   else
     return false
   end
end

a = parse(fileContent) --position of V in content 
print(a)
print(string.sub(fileContent, a)) -- content until first found V 

在这个例子中,我在位置 21 处找到了第一个 V。因此,除了 64 字节或整个文件之外,只读取 21 字节会很酷。但是然后我需要在阅读内容之前找到位置。这可能吗? (21byte是可变的,可能是20或50等等)

您可以使用 file:seek and read a certain number of characters (bytes) by providing an integer to file:read

指定文件位置
local file = file:open(somePath)
if file then
  -- set cursor to -5 bytes from the file's end
  file:seek("end", -5)
  -- read 3 bytes
  print(file:read(3))
  file:close()
end

您不能在不阅读文件的情况下搜索文件。如果您不想读取整个文件,您可以通过按行读取(如果文件中有行)或每次读取特定数量的字节直到找到某些内容来分块读取它。 当然你也可以阅读byte-wise.

您可以争论是将 64 字节文件作为一个整体还是以块的形式读取更有意义。我的意思是在大多数情况下您不会注意到任何差异。

所以你可以 file:read(1) 在一个循环中,一旦你找到 V 或到达文件末尾就终止。

local file = io.open(somePath)
if file then
  local data = ""
  for i = 1, 64 do
    local b = file:read(1) 
    if not b then print("no V in file") data = nil break end
    data = data .. b
    if b == "V" then print(data) break end
  end
  file:close()
end

local file = io.open("d:/test.txt", "r")
if file then  
  local data = file:read("a")
  local pos = data:find("V")
  if pos then
      print(data:sub(1, pos))
  end
  file:close()
end

(或)将您的代码更正为...

local function read_file(path)
  local file = io.open(path, "r") -- r read mode and b binary mode
  if not file then return nil end
  local content = file:read(64) -- reading 64 bytes
  file:close()
  return content
end

local fileContent = read_file("test/l_0.dat") -- '../' causing error
print(fileContent)

local function parse(line)
   if line then
     local len = 1
     local a = line:find("V", len +1) --find V in content 
     return a
   else
     return false
   end
end

print(fileContent:sub(1, parse(fileContent))) -- content until first found V

那就是……

0123456789VabcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ

0123456789V

如果您希望 V 是一个(单个)分隔符,您可能不想把它放出来。
满足string.sub(text, start, stop)的实力...

print(fileContent:sub(1, parse(fileContent) - 1))  -- before V                             
-- 0123456789
print(fileContent:sub(parse(fileContent) + 1, -1)) -- after V
-- abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ