二进制“尾部”文件

问题描述 投票:0回答:9

我猜这个网站上的大多数人都熟悉 tail,如果不熟悉的话 - 它提供了一种“跟随”模式,当文本附加到文件 tail 时,会将这些字符转储到终端。

我正在寻找(如果需要的话可能自己编写)是一个适用于二进制文件的 tail 版本。基本上,我有一个无线链接,我想在文件从另一个网络链接下来时通过该链接进行传输。查看尾部源代码,重写不会太难,但我宁愿不重新发明轮子!严格来说,这并不是“尾部”,因为我希望复制整个文件,但它会监视添加的新字节并传输这些字节。

想法?

c tail gnu-coreutils gnu-fileutils
9个回答
22
投票

通过管道将其传输到 hexdump:

tail -f somefile | hexdump -C

6
投票

还有 bintail 应用程序,它似乎比上述脚本更强大。

bintail 软件包包含一个应用程序bintail。该程序从磁盘读取普通文件,并将输出逐字节传输到标准输出,无需翻译,类似于 tail(1) 对文本文件的操作。这对于实时写入时“拖尾”二进制文件(例如 WAV 文件)非常有用。这个应用程序正在开发中,但它已经完成了它为我设计的任务。


5
投票

Linux coreutils tail(1) 在二进制文件上工作得很好。对于大多数应用程序,您只需要避免其行方向,以便输出不会从数据结构中间的某个随机点开始。您只需从文件开头开始即可做到这一点,这也正是您所要求的:

tail -c +1 -f somefile

效果很好。


3
投票

这个为 Windows 匆忙编码的 Python 脚本可能会有所帮助:

# bintail.py -- reads a binary file, writes initial contents to stdout,
# and writes new data to stdout as it is appended to the file.

import time
import sys
import os
import msvcrt
msvcrt.setmode(sys.stdout.fileno(), os.O_BINARY)

# Time to sleep between file polling (seconds)
sleep_int = 1

def main():
    # File is the first argument given to the script (bintail.py file)
    binfile = sys.argv[1]

    # Get the initial size of file
    fsize = os.stat(binfile).st_size

    # Read entire binary file
    h_file = open(binfile, 'rb')
    h_bytes = h_file.read(128)
    while h_bytes:
        sys.stdout.write(h_bytes)
        h_bytes = h_file.read(128)
    h_file.close()


    # Loop forever, checking for new content and writing new content to stdout
    while 1:
        current_fsize = os.stat(binfile).st_size
        if current_fsize > fsize:
            h_file = open(binfile, 'rb')
            h_file.seek(fsize)
            h_bytes = h_file.read(128)
            while h_bytes:
                sys.stdout.write(h_bytes)
                h_bytes = h_file.read(128)
            h_file.close()
            fsize = current_fsize
        time.sleep(sleep_int)

if __name__ == '__main__':
    if len(sys.argv) == 2:
        main()
    else:
        sys.stdout.write("No file specified.")

1
投票

less somefile

然后按

shift F


1
投票

严格来说,您需要编写一个程序来执行此操作,因为

tail
未指定用于处理二进制文件。如果您想尽快接收新的“滴流”数据,您可能还需要避免缓冲问题。


0
投票

这不是尾部——这是逐步复制文件。看看rsync。


0
投票

我使用它,因为它也适用于直播:

cat ./some_file_or_dev | hexdump -C

转储我的按键(和释放)的示例:

[user@localhost input]$ sudo cat /dev/input/event2 | hexdump -C
00000000  81 32 b1 5a 00 00 00 00  e2 13 02 00 00 00 00 00  |.2.Z............|
00000010  04 00 04 00 36 00 00 00  81 32 b1 5a 00 00 00 00  |....6....2.Z....|
00000020  e2 13 02 00 00 00 00 00  01 00 36 00 01 00 00 00  |..........6.....|
00000030  81 32 b1 5a 00 00 00 00  e2 13 02 00 00 00 00 00  |.2.Z............|
00000040  00 00 00 00 00 00 00 00  81 32 b1 5a 00 00 00 00  |.........2.Z....|
00000050  a3 af 02 00 00 00 00 00  04 00 04 00 36 00 00 00  |............6...|
00000060  81 32 b1 5a 00 00 00 00  a3 af 02 00 00 00 00 00  |.2.Z............|
^C

0
投票

我使用这个命令(1表示要解释的字节数): 尾-f | od-x1

© www.soinside.com 2019 - 2024. All rights reserved.