2013-06-21 35 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