I like php’s file_put_content function, which can write a string to a file with single line of code:
Few languages have such powerful function. In C language, you need to open a file first, set some strange open mode, call the write function to write actual content, and close the file in the end. That is really troublesome as we just want to write a string to a file which should be done in a line of code.
Although file_put_content is easy to use, you may wonder how to append to file instead of overwriting existed file. The above code will overwrite the existing file with the new content. To append to file, you should use the FILE_APPEND flag:
Now the string “content” is appended to file.txt. If file.txt does not exist, it is created and the string is put into the newly created file.
Note that this function does not add new line to the string automatically. So, if you call it multiple times, the strings will be concated together without line breaks between them. Typically, you may want to append a new line after the string so that every string will be put on a new line. You need to append new lines manually: