From the course: Complete Guide to C Programming Foundations

Unlock the full course today

Join today to access over 24,300 courses taught by industry experts.

Solution: Writing and reading files

Solution: Writing and reading files - C Tutorial

From the course: Complete Guide to C Programming Foundations

Solution: Writing and reading files

(upbeat music) - [Instructor] Here's my solution, starting with the code skeleton provided. I need a few more variables beyond the file name and I'll add them here. The file name is created as a constant character. It never changes throughout the program. Two buffers are used though you could be economical and use only one. This code uses only one file handle, though you could have two. It's all up to you. The first task is to open and create a file for writing. Use W as the mode and check for any errors. The file mode is W for writing and then immediately a test is made to see if the file handle is null. If so, an error message is output and the program quits. The next step is to prompt for input from the user to get their name. I'll explain why I'm using scanf. It's not one of my favorite functions, but I do have a reason and I'll give that to you in a minute. The next step is to write this name to the file along with the string. The fprintf function requires the file handle as its…

Contents