2014-05-03 35 views
0

我有以下代碼從文件OCaml的讀 n字符

let read_file filename = 
    let lines = ref [] in 
    let chan = open_in filename in 
    try 
    while true do 
     lines := input_line chan :: !lines 
    done; 
    !lines 
    with End_of_file -> 
    close_in chan; 
    List.rev !lines 

讀線。然而,該代碼添加了額外的「\」字符「\ n」。
E.g.

helloworld\n 

被讀入

helloworld\\n 

我應如何關閉這讓我得到helloworld\n呢?
非常感謝!

編輯

所以我跟這個測試:

let read_file filename = 
    let lines = ref [] in 
    let chan = open_in filename in 
    try 
    while true do 
     lines := input_line chan :: !lines 
    done; 
    !lines 
    with End_of_file -> 
    close_in chan; 
    List.rev !lines 

let() = 
    let lines = read_file "test.txt" in 
    for i=1 to List.length lines 
    do 
    Printf.printf("%s") (List.nth lines (i-1)) 
    done; 

的test.txt

helloworld\n 

輸出是helloworld\n而不是helloworld用一個新行。

回答

2

我嚴重懷疑這段代碼引入了多餘的字符。很可能你只是誤讀了頂層的輸出。如果你用print_string寫出字符串,你會看到實際的內容。

我假設你的輸入行實際上包含helloworld\n(12個字符,再加上最後的換行符)。

這裏是在OS X 10.9.2

$ od -c myfile 
0000000 h e l l o w o r l d \ n \n   
0000015 
$ ocaml 
     OCaml version 4.01.0 

# let read_file filename = 
... copy your definition above ... 
# let lines = read_file "myfile";; 
val lines : string list = ["helloworld\\n"] 
# String.length (List.nth lines 0);; 
- : int = 12 
# print_string (List.nth lines 0);; 
helloworld\n- : unit =() 

行長度是正確的(12個字符)的測試會話。額外的反斜槓只是頂層在字符串中寫入反斜槓的方式。

更新

您的測試文件顯然包含實際\n(兩個字符),所以自然這是對輸出顯示的內容。如果你不想做\n在輸出中顯示出來,你應該從輸入中刪除它:-)

更新2

我不能動搖,你可以不使用感受在低層次上思考文本文件。如果這是真的,那麼需要考慮一些事情。

  • 線在Unix風格的文本文件已經在結尾處換行。您不需要在文件中輸入\n來表示行結束。您的文本編輯器(或其他文本處理應用程序)會在行尾添加換行符。

  • OCaml的功能input_line刪除這些新行(因爲它們是多餘的 - 有一個在每行的末尾)。

  • 如果您希望這些換行符出現在行列表中,您可以使用input_line chan^"\n"或類似的方法將它們自己添加回來。

  • 或者您可以使用print_endline寫出線條,爲您寫入換行符。

(我的道歉,如果你已經知道這件事。)

+0

感謝您的幫助。是的,我得到了同樣的結果。我可能誤解了這個錯誤,但是我想讓「helloworld \ n」這樣,當我運行print時,它會打印出「helloworld」和一個新行,而不是「\ n」。 – Ra1nWarden

+1

這就是打印字符串時會執行的操作。它只是頂級顯示額外的反斜槓(以消除解釋REPL結果時的不明確性)。 –

+0

嗯。我想在打印輸出時將'\ n'渲染爲新行...... – Ra1nWarden

0

這裏是我做了解析與Str.regexp

let newlinereg = Str.regexp "\\\\n" in                                      
let replacednewline = Str.global_replace newlinereg "\n" output_string in                                        
let tabreg = Str.regexp "\\\\t" in                                     
let final_string = Str.global_replace tabreg "\t" replacednewline in 
final_string;;