如何在Ruby中读取文件,每次读取字节?

时间:2021-11-15 05:09:55

I want to iteratively read a fixed number of bytes in a file, and return them

我想迭代地读取文件中的固定字节数,并返回它们

My code is below. I have taken it from an example on the internet

我的代码如下。我从互联网上的一个例子中得到的

File.open('textfile.txt') do |file|
  while (buffer = file.read(size)) do
     yield buffer
  end
end

I get the error no block given.

我得到的错误没有一个块给出。

2 个解决方案

#1


5  

Well, that's because no block is given. You can either replace yield buffer with puts buffer (or any operation you want) or create a separate method taking code block:

那是因为没有block被给定。您可以用put缓冲区(或任何您想要的操作)替换掉yield buffer,也可以使用代码块创建一个单独的方法:

def read_file
  File.open('textfile.txt') do |file|
    while (buffer = file.read(size)) do
      yield buffer
    end
  end
end

and call it like this

这样命名

read_file do |data|
  // do something with data
  puts data 
end

Add normal parameters (like file name or block size) to read_file, if necessary.

如果需要,向read_file中添加常规参数(如文件名或块大小)。

#2


4  

I don't know what you're trying to do with yield there. Yield is something you use inside of a block you're intending to repeatedly call, like an Enumerator. It's much easier to just do something like this.

我不知道你要怎么处理产量。Yield是您在要反复调用的块中使用的东西,如枚举数。做这样的事情要容易得多。

File.open('test.txt') do|file|
  until file.eof?
    buffer = file.read(10)
    # Do something with buffer
    puts buffer
  end
end

#1


5  

Well, that's because no block is given. You can either replace yield buffer with puts buffer (or any operation you want) or create a separate method taking code block:

那是因为没有block被给定。您可以用put缓冲区(或任何您想要的操作)替换掉yield buffer,也可以使用代码块创建一个单独的方法:

def read_file
  File.open('textfile.txt') do |file|
    while (buffer = file.read(size)) do
      yield buffer
    end
  end
end

and call it like this

这样命名

read_file do |data|
  // do something with data
  puts data 
end

Add normal parameters (like file name or block size) to read_file, if necessary.

如果需要,向read_file中添加常规参数(如文件名或块大小)。

#2


4  

I don't know what you're trying to do with yield there. Yield is something you use inside of a block you're intending to repeatedly call, like an Enumerator. It's much easier to just do something like this.

我不知道你要怎么处理产量。Yield是您在要反复调用的块中使用的东西,如枚举数。做这样的事情要容易得多。

File.open('test.txt') do|file|
  until file.eof?
    buffer = file.read(10)
    # Do something with buffer
    puts buffer
  end
end