php - different ways to open a file
For many different technical reasons, PHP requires you to specify
your intentions when you open a file. Below are the three basic ways to open a
file and the corresponding character that PHP uses.
- Read: 'r'
Open a file for read only use. The file pointer begins at the
front of the file.
- Write: 'w'
Open a file for write only use. In addition, the data in the file
is erased and you will begin writing data at the beginning of the file. This is also called
truncating a file, which we will talk about more in a later lesson. The file
pointer begins at the start of the file.
- Append: 'a'
Open a file for write only use. However, the data in the file is
preserved and you begin will writing data at the end of the file. The file pointer begins
at the end of the file.
A file pointer is PHP's way of remembering its
location in a file. When you open a file for reading, the file pointer begins
at the start of the file. This makes sense because you will usually be reading
data from the front of the file.
However, when you open a file for appending, the file pointer is
at the end of the file, as you most likely will be appending data at the end of
the file. When you use reading or writing functions they begin at the location
specified by the file pointer.
php - file open: advanced
There are additional ways to open a file. Above we stated the
standard ways to open a file. However, you can open a file in such a way that
reading and writing is allowable! This combination is done by placing a plus
sign "+" after the file mode character.
- Read/Write: 'r+'
Opens a file so that it can be read from and written to. The file
pointer is at the beginning of the file.
- Write/Read: 'w+'
This is exactly the same as r+, except that it deletes all information in the
file when the file is opened.
- Append: 'a+'
This is exactly the same as r+, except that the file pointer is at the end of
the file.
Comments
Post a Comment
Thank you for your Comment