Using C to Append text to a File using the Linux Command Line

February 22nd, 2009
By: Cory Mathews

Damn I think the title is almost as long as the entire post…

Any way, here is a quick tip that will allow your c program to easily add text to the end of a file without ever having to deal with the file in your code. This is accomplished by a simple system call, take a look at the following example.

int main() {
  system("ls >> 1.txt");

This simple code will perform the ls command and redirect its output to the file 1.txt. If 1.txt does not exist it will create the file. If the file exists it will append the output from ls to the file.