Open In App

What is the difference between fopen modes “r+”, “rw+” and “w+” in PHP?

Last Updated : 07 May, 2020
Improve
Improve
Like Article
Like
Save
Share
Report

File handling is a very important part of programming when it comes to making applications. We might require reading input from a file or writing output into a file. File handling in PHP is similar to other programming languages. There are predefined functions that can be used to accomplish the specified task. Check out the Basics of File Handling to know about the functions.

Syntax:

$<variable_name> = fopen(<file source path>,<access mode>)

Difference in the fopen modes r+, rw+ and w+ in PHP

  • r+: Opens a file in read and write mode. File pointer starts at the beginning of the file.
  • w+: Opens a file in read and write mode. It creates a new file if it does not exist, if it exists, it erases the contents of the file and the file pointer starts from the beginning.
  • rw+: Opens a file in read and write mode. File pointer starts at the beginning of the file. This mode does not exists in the PHP documentation but it works well.

Example: For a better understanding, let us observe the parsing function for fopen.

  • It checks for the first character of the argument, i.e. mode[0]. Depending upon it being r,w,a or x, corresponding mode is identified.
  • It looks for the presence of ‘+’ in the mode argument. If present, it sets the appropriate flags.

Therefore, “r+” and “w+” has a difference in the mode of opening the file and placing the file pointer. The “r+” and “rw+” are the same. PHP only cares that the string starts with “r” and has a “+”. The “w” is ignored in “rw+”. Hence, they work the same.




PHPAPI int php_stream_parse_fopen_modes(const char *mode, int *open_flags)
{
    int flags;
  
    switch (mode[0]) {
        case 'r':
            flags = 0;
            break;
        case 'w':
            flags = O_TRUNC|O_CREAT;
            break;
        case 'a':
            flags = O_CREAT|O_APPEND;
            break;
        case 'x':
            flags = O_CREAT|O_EXCL;
            break;
        case 'c':
            flags = O_CREAT;
            break;
        default:
            /* unknown mode */
            return FAILURE;
    }
  
    if (strchr(mode, '+')) {
        flags |= O_RDWR;
    } else if (flags) {
        flags |= O_WRONLY;
    } else {
        flags |= O_RDONLY;
    }
  
#if defined(O_CLOEXEC)
    if (strchr(mode, 'e')) {
        flags |= O_CLOEXEC;
    }
#endif
  
#if defined(O_NONBLOCK)
    if (strchr(mode, 'n')) {
        flags |= O_NONBLOCK;
    }
#endif
  
#if defined(_O_TEXT) && defined(O_BINARY)
    if (strchr(mode, 't')) {
        flags |= _O_TEXT;
    } else {
        flags |= O_BINARY;
    }
#endif
  
    *open_flags = flags;
    return SUCCESS;
}




Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads