Save Text to a File in C

I had an occasion to learn a little about programming in C for the first time. One thing I needed to be able to do was save text to a file, but it was hard to find help for this on the Internet. This may be because it is called something slightly different in C than what I’m used to.

Anyway, below is some sample code.

#include  <stdio.h>
 
FILE *fp;
fp = fopen("/home/Bill/path/test.txt", "w");
fprintf(fp, "%-15.15s\n", "Hello, world!");
fclose(fp);

That should get you started at least. There are other options, such as appending to a file (example below), writing numbers, etc.

fp = fopen("/home/Bill/path/test.txt", "a");

Leave a Reply