2012-10-06 24 views
2

通過向該作用域發送查詢,從一個.gif格式的作用域讀取打印屏幕圖像。返回的數據是二進制塊形式。我通過套接字連接和使用tcl與此範圍進行通信。我可以很好地讀取數據,但是當我嘗試將數據寫入本地文件時,它似乎沒有正確寫入,因爲創建的文件中沒有任何信息。目標:將這些數據保存或寫入本地文件,以便以後訪問。將.gif數據從作用域讀入到tcl中並寫入本地文件

下面是一段代碼,試圖完成TCL中的任務。

#reading .gif data(binary block form) and writing it to a local file 

fconfigure $channelid -encoding binary -translation binary ; #converts the stdin to binary data input 
fconfigure $fileId -encoding binary -translation binary ; #converts the stdout to binary data output 
set image [getdata $channelid "some query?"] ;# getdata proc reads the query returned data 
puts stderr $image ;#to verify what data I am reading 
set filename "C:/test.gif" 
set fileId [open $filename "w"] 
puts -nonewline $fileId $image 
close $fileId 

任何想法或幫助將不勝感激。謝謝。

回答

2

GIF數據基本上是二進制的;當你寫出來的時候,你需要把它寫成二進制,或者Tcl會對它進行一些轉換(例如,編碼轉換),這些轉換對於文本數據是正確的,但對於二進制文件是錯誤的。最簡單的方法是使用wb模式打開,而不是使用w,如果您使用的Tcl版本支持該模式 - 它在8.5中引入使事情更像C stdio - 但在打開後使用fconfigure $fileId -translation binary在寫任何數據之前。

請注意,Tcl 總是立即對事物進行操作;在打開它之前,您不能fconfigure頻道。我猜你的第二個fconfigure真的是太早了。將代碼轉換爲一個過程以便它不處理全局變量可能是一個好主意;這可以幫助您檢測各種與操作訂貨更容易的問題:

proc copy_data {source_channel query_string target_file} { 
    # -translation binary implies -encoding binary (and a few other things too) 
    fconfigure $source_channel -translation binary 
    set image [getdata $source_channel $query_string] 
    set fileId [open $target_file "wb"] 
    puts -nonewline $fileId $image 
    close $fileId 
} 

# Invoke to do the operation from your example 
copy_data $channelid "some query?" "C:/test.gif" 
+0

OK,一些Tcl的直接操作的安排事情後來發生或定義,以後用於事物,但調度/定義_itself_立即發生。 –

+0

非常感謝您的幫助。我得到了它的工作:) – shokii

相關問題