2008-10-24 108 views
11

我猜這個網站上的大多數人都熟悉尾巴,如果不是的話 - 它提供了一個「追隨」模式,當文本被追加到文件尾部時,會將這些字符轉儲到終端。二進制「尾巴」文件

我在找什麼(如果需要可能寫自己)是一個處理二進制文件的尾部版本。基本上我有一個無線鏈接,我想從另一個網絡鏈接下載一個文件。回顧尾部源代碼,重寫不會太難,但我寧願不重新發明輪子!這並不是嚴格意義上的「尾巴」,因爲我希望複製整個文件,但它會在新字節被添加和流式傳輸時觀察。

想法?

回答

5

還有這似乎是比上述腳本更健壯的bintail應用。

bintail包包含一個應用程序,bintail。該程序從磁盤讀取正常文件,並將輸出管道輸出爲逐字節,無需翻譯的標準輸出,類似於對文本文件所做的尾部(1)。這對於「實時」寫入二進制文件(如WAV文件)時很有用。這個應用程序正在進行中,但它已經完成了它爲我設計的目的。

12

管它進制打印:

tail -f somefile | hexdump -C 
+0

哇我不認爲這會工作 – MattSmith 2008-10-24 01:48:05

+0

我不是100%確定自己,但我試了一下,它工作得很好。 – 2008-10-24 01:51:27

+1

當-f僅在二進制文件中看到一個換行符時纔會輸出新數據?我懷疑它不會輸掉標準輸出。 – Chris 2008-10-24 01:59:07

1

less somefile

然後按shift F

0

這不是尾巴 - 這是逐步複製文件。看看rsync。

1

嚴格地說,您需要編寫一個程序來執行此操作,因爲tail未指定用於二進制文件。如果您希望儘快收到新的「滴漏」數據,也可能需要避免緩衝問題。

2

爲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

Linux coreutils tail(1)在二進制文件上工作得很好。對於大多數應用程序,您只需避免其行定向,以便輸出不在數據結構中間的某個隨機點開始。你可以做到這一點,只需在開始文件的開頭,這也正是你問什麼:

tail -c +1 -f somefile

的作品就好了。