How to write to a CSV file in C
Austin Repp
Posted on November 17, 2020
Writing to a CSV using C code
A basic CSV file relies on a comma-separated data format, which makes it straightforward to write to this file type from a c program.
First you will want to create a file pointer, which will be used to access and write to a file. Then we call fopen
on this file pointer, passing in the name of the file we want to write to. In this scenario, I don't yet have a file called "MyFile.csv". A file with that name will automatically be created.
FILE *fpt;
fpt = fopen("MyFile.csv", "w+");
Next I will show how to use fprintf
to write data to the file pointer. The line below shows how a row of column headers can first be written to the file. Notice how the values are comma-separated, and there is a "\n" at the end, indicating that it should go to the next row.
fprintf(fpt,"ID, Name, Email, Phone Number\n");
Once the header row is written, we can loop through our data, and write each index (in this case a person) to a row in the CSV file. The following would be placed in a loop, with each index being a different person.
fprintf(fpt,"%d, %s, %s, %s\n", id, name, email, phone);
After writing each row, we can close the file pointer.
fclose(fpt);
That's it! Your file will now contain however many rows of data have been written to it.
Posted on November 17, 2020
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.