How to Write to a file in C

Writing to a file in c is surprisingly simple. Most of the steps in c can be found in most other languages as well. In c you open a file, write to it and close it again. In most languages you either do the same exact steps - or have a higher level construct that does the same thing for you - but every language will ultimately make the same sys-calls that the c languages shows us directly.

First include stdlib (for getting the exit call to work) and stdio to get the file handling functions and data types.

Next open the file, saving the pointer in f. Check if f is null - and exit early if it is (that means we could not open the file for writing).

Finally write the string (here a c-string written with fprintf to the stream f points to). You could write anything this way, as long as fprintf can “print” it.

Just before we close the program, we close the filestream (even though that would have happened implicitly when exiting - it is a good habit to get, since you might some day do file IO some place other than main().