tags:

views:

208

answers:

3

when I use fopen function , why don't I use r+ always , even when I'm not going to write any thing ... is there a reason for separating writing/reading process from only reading ..

like , the file is locked for reading when I use r+ , because i might write new data into it or something ...

another question : in php manual

a+ : Open for reading and writing; place the file pointer at the end of the file. If the file does not exist, attempt to create it.

What is supposed to be read if you are at the end of the file ..(pointer at the end) !!?

where to learn more about the filesystem thing .... it's confusing

A: 

r+ allocates a tiny bit more at the OS level versus r, but it's not enough to really worry about.

Reading at the end of a file will return EOF; in PHP this is shown by fread() returning an empty string.

The modes are described in the fopen(3) man page.

Ignacio Vazquez-Abrams
So , I may always use r+ , a+ , w+ ?
Naughty.Coder
If the underlying filesystem supports it, sure. You may have issues when using a read-only or write-only (yes, those do exist) filesystem.
Ignacio Vazquez-Abrams
A: 

According to the manual page of fopen :

  • r+ means "Open for reading and writing"
  • r means "Open for reading only"
  • In both cases, the cursor will be placed at the beginning of the file.

Im guessing a couple of differences would be :

  • Witf r+, if the file is write-locked, you won't be able to read it
  • Opening for writing (i.e. r+) probably requires a bit more resources.

So, if you only need to read from the file, you should use r, and not r+ -- afterall, r means "reading" (Generally speaking, you should not ask for more than you need).


About your a+ question : even if you are at the end of the file when it's opened, you can use fseek to change the cursor's position in the file.

Which means you are not limited to the end of the file : if needed, you can read from elsewhere.

Pascal MARTIN
+1  A: 

r vs r+: r+ will actually open file for reading and writing but will place poitner in the beginning. Will not truncate/delete file (unlike w/w+), so you can read and overwrite file data

w vs w+: w and w+ will create/delete file, w+ will also allow you to read (so if you write you can use fseek to re-read what you wrote). Note file will be erased in both cases and original content will be lost. With w+ you may use fseek to go back and overwrite data in file (instead of recreating the file for a minor change)

a vs a+: a will open for writing, a+ will also allow reading. The file will not be truncated and you can use fseek to move back/forward. The pointer will be placed in the end. a+ is just like r+ but instead will have the pointer at the end - saves one fseek command if you need to write/append first then correct

x vs x+: this is just like w/w+ but will fail if file exists (i.e. never truncate/delete file)

Vals