1

It is said, that fopen can use t mode to convert \n to \r\n. So, questions:

1) How should i use t mode when i need to read and write (r+)? Should it be r+t or rt+ or tr+? Same question for b, should i write r+b or how?

2) I've tried all variants on debian linux to convert file, that contains only \n to \r\n using magic mode t (wanna understand how it works). But it does not work. What am I doing wrong? When t mode works?

Here is my code:

// 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);
Funk Forty Niner
  • 74,450
  • 15
  • 68
  • 141
avasin
  • 9,186
  • 18
  • 80
  • 127

1 Answers1

2

From: http://php.net/fopen

Windows offers a text-mode translation flag ('t') which will transparently translate \n to \r\n when working with the file. In contrast, you can also use 'b' to force binary mode, which will not translate your data. To use these flags, specify either 'b' or 't' as the last character of the mode parameter.

So no Linux. Also, according to the spec r+t or r+b would be correct (but only on Windows).

Halcyon
  • 57,230
  • 10
  • 89
  • 128
  • Hmm.. so, if developer expect his code to be run sometime under windows, he should use just b not to corrupt data, right? I'll check how it works under windows, thx – avasin Jun 21 '13 at 16:13
  • P.S. Can you give a link to the spec please? (for `r+b` syntax)? – avasin Jun 21 '13 at 16:13
  • I linked it AND it's in the quote I posted. – Halcyon Jun 21 '13 at 16:14
  • I know where are docs for fopen function in php, but i can't see any examples, showing that `r+b` or `r+t` is correct syntax (excluding user's comments with negative rating) – avasin Jun 21 '13 at 16:28
  • 1
    > To use these flags, specify either 'b' or 't' as the **last** character of the mode parameter. --- So unless the doc lies, `r+t` and `r+b` are correct, again NOT ON LINUX. – Halcyon Jun 21 '13 at 16:30
  • I will read docs carefully. I will read docs carefully. I will read docs carefully. Thx! – avasin Jun 21 '13 at 16:44
  • 1
    It is worth noting that the `b` and `t` flags won't trigger a notice, warning or error on Linux, they will simply be ignored. – MrWhite Oct 26 '13 at 00:49