Challenge - 5 Problems
File Open Modes Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate2:00remaining
What is the output of this PHP code when opening a file in 'r' mode?
Consider the following PHP code snippet. What will it output if the file 'example.txt' exists and contains the text 'Hello World'?
PHP
<?php $handle = fopen('example.txt', 'r'); $content = fread($handle, 5); echo $content; fclose($handle); ?>
Attempts:
2 left
💡 Hint
The 'r' mode opens the file for reading from the beginning.
✗ Incorrect
The fread function reads 5 bytes from the file starting at the beginning, so it outputs 'Hello'.
❓ Predict Output
intermediate2:00remaining
What happens when opening a non-existent file in 'r' mode?
What will the following PHP code output if 'nofile.txt' does not exist?
PHP
<?php $handle = fopen('nofile.txt', 'r'); if (!$handle) { echo 'Failed to open file'; } else { echo 'File opened'; } ?>
Attempts:
2 left
💡 Hint
The 'r' mode requires the file to exist.
✗ Incorrect
Opening a non-existent file in 'r' mode returns false, so the code prints 'Failed to open file'.
❓ Predict Output
advanced2:00remaining
What is the output when writing to a file opened in 'w' mode?
Given the file 'data.txt' contains 'Old Data', what will be the content of the file after running this PHP code?
PHP
<?php $handle = fopen('data.txt', 'w'); fwrite($handle, 'New Data'); fclose($handle); $contents = file_get_contents('data.txt'); echo $contents; ?>
Attempts:
2 left
💡 Hint
The 'w' mode truncates the file before writing.
✗ Incorrect
Opening a file in 'w' mode clears its contents, so after writing 'New Data', the file contains only that.
❓ Predict Output
advanced2:00remaining
What will be the output when appending to a file with 'a' mode?
If 'log.txt' initially contains 'Line1\n', what will be the content after running this PHP code?
PHP
<?php $handle = fopen('log.txt', 'a'); fwrite($handle, 'Line2\n'); fclose($handle); $contents = file_get_contents('log.txt'); echo $contents; ?>
Attempts:
2 left
💡 Hint
The 'a' mode adds data to the end of the file without deleting existing content.
✗ Incorrect
The 'a' mode appends 'Line2\n' after the existing 'Line1\n', so the file contains both lines.
🧠 Conceptual
expert2:00remaining
Which file open mode allows reading and writing without truncating the file?
In PHP, which file open mode lets you read and write to a file without deleting its existing content at open?
Attempts:
2 left
💡 Hint
One mode opens the file for reading and writing but does not clear it.
✗ Incorrect
'r+' opens the file for reading and writing starting at the beginning without truncating the file. 'w+' truncates the file. 'a+' opens for reading and writing but places the pointer at the end for writing. 'x+' creates a new file and fails if it exists.