2013-06-21 34 views
1

據說,fopen可以使用t模式將\n轉換爲\r\n。所以,問題:fopen't'兼容模式php

1)我應該如何使用t模式當我需要讀寫(r+)?應該是r+t還是rt+tr+b同樣的問題,我應該寫r+b或如何?

2)我試過在Debian Linux上所有變體轉換文件,包含使用魔法模式t\n\r\n(想了解它是如何工作)。但它不起作用。我究竟做錯了什麼?當t模式工作?

這裏是我的代碼:

// Write string with \n symbols 
$h = fopen('test.file', 'wt'); 
fwrite($h, "test \ntest \ntest \n"); // I've checked, after file is being created 
fclose($h);       // \n symbols are not substituted to \r\n 

// Open file, that contains rows only with \n symbols 
$h = fopen('test.file', 'rt'); 
$data = fread($h, filesize('test.file')); 
fclose($h); 

// I want to see what's inside 
$data = str_replace("\n", '[n]', $data); 
$data = str_replace("\r", '[r]', $data); 

// finally i have only \n symbols, \r symbols are not added 
var_dump($data); 

回答

2

來源:http://php.net/fopen

的Windows提供了一個文本轉換標記( 'T'),將\ n透明地轉換爲\ r \當處理文件時。相反,您也可以使用'b'強制執行二進制模式,這將不會轉換您的數據。要使用這些標誌,請指定'b'或't'作爲模式參數的最後一個字符。

所以沒有Linux。此外,根據規範r+tr+b將是正確的(但只在Windows上)。

+0

嗯..所以,如果開發人員希望他的代碼能夠在Windows下運行,他應該只使用b而不是破壞數據,對吧? 我會檢查它是如何在windows下工作的,thx – avasin

+0

P.S.你能給一個鏈接到規範嗎? (對於'r + b'語法)? – avasin

+0

我把它鏈接起來,它在我發佈的報價中。 – Halcyon