This course will be retired on June 1, 2025.
Heads up! To view this whole video, sign in with your Courses account or enroll in your free 7-day trial. Sign In Enroll
Start a free Courses trial
to watch this video
Writing files builds upon the same approaches as reading files. Writing files will allow us to save any changes we make, and also allow us to change settings and update application details.
Download: File Handling Cheat Sheet
Be careful when manipulating files!
You can do a lot of damage if you do something wrong. Common errors are: editing the wrong file, filling a hard-drive with garbage data, and deleting the content of a file by accident.
PERMISSIONS
If you are having problems with accessing files, a good place to start looking is at the file permissions. To learn more about file permissions, check out our Console Foundations course, specifically the video on File Permissions
File Functions and Modes
fopen() — Opens file or URL
fwrite() — Binary-safe file write
fputs() — Alias of fwrite
fclose() — Closes an open file pointer
For more functions and options, check out the documentation for Directory Functions and File System Functions.
Modes | Description |
---|---|
r | Open a file for read only. File pointer starts at the beginning of the file |
w | Open a file for write only. Erases the contents of the file or creates a new file if it doesn't exist. File pointer starts at the beginning of the file |
a | Open a file for write only. The existing data in file is preserved. File pointer starts at the end of the file. Creates a new file if the file doesn't exist |
x | Creates a new file for write only. Returns FALSE and an error if file already exists |
r+ | Open a file for read/write. File pointer starts at the beginning of the file |
w+ | Open a file for read/write. Erases the contents of the file or creates a new file if it doesn't exist. File pointer starts at the beginning of the file |
a+ | Open a file for read/write. The existing data in file is preserved. File pointer starts at the end of the file. Creates a new file if the file doesn't exist |
x+ | Creates a new file for read/write. Returns FALSE and an error if file already exists |
Related Discussions
Have questions about this video? Start a discussion with the community and Treehouse staff.
Sign upRelated Discussions
Have questions about this video? Start a discussion with the community and Treehouse staff.
Sign up
You need to sign up for Treehouse in order to download course files.
Sign upYou need to sign up for Treehouse in order to set up Workspace
Sign up