This is a text-only version of the following page on https://raymii.org: --- Title : C++ create and write to a CSV file Author : Remy van Elst Date : 07-06-2019 Last update : 16-06-2019 URL : https://raymii.org/s/snippets/Cpp_create_and_write_to_a_csv_file.html Format : Markdown/HTML --- In this quick snippet I'll show you how to create and write to a csv file. It includes checking if the file is writable, and if it's not there, creates it with a different first row as header. It's a quick example, I've used it to log some test data. It can probably be improved. It does use a mutex and `guard_lock` so it should be thread safe. I've updated this snippet to use a variadic template. [Click here to view the new snippet][1].

Recently I removed all Google Ads from this site due to their invasive tracking, as well as Google Analytics. Please, if you found this content useful, consider a small donation using any of the options below:

I'm developing an open source monitoring app called Leaf Node Monitoring, for windows, linux & android. Go check it out!

Consider sponsoring me on Github. It means the world to me if you show your appreciation and you'll help pay the server costs.

You can also sponsor me by getting a Digital Ocean VPS. With this referral link you'll get $200 credit for 60 days. Spend $25 after your credit expires and I'll get $25!

### write_csv.cpp The first method checks if the file exists. The second method is a template, but with a set amount of columns (since that was enough in my case). The types could differ which is why I opted for a template. Note that this is a cut-down simplified example, in the next section I list some possible improvements. Since this was a one-off user story for some tests, the time allocated wasn't much, thus making the code bare. In `main()` there is an example with different types and a loop to show how you could use the function. #include #include #include std::mutex logMutex; bool fileExists(std::string& fileName) { return static_cast(std::ifstream(fileName)); } template bool writeCsvFile(filename &fileName, T1 column1, T2 column2, T3 column3) { std::lock_guard csvLock(logMutex); std::fstream file; file.open (fileName, std::ios::out | std::ios::app); if (file) { file << "\"" << column1 << "\","; file << "\"" << column2 << "\","; file << "\"" << column3 << "\""; file << std::endl; return true; } else { return false; } } int main() { std::string csvFile = "logfile2.csv"; std::string naam = "Hallo"; if(!fileExists(csvFile)) writeCsvFile(csvFile, "header1", "header2", "header3"); for (int i = 1; i < 10; ++i) { if (!writeCsvFile(csvFile, i, naam, static_cast(i * 3.5))) { std::cerr << "Failed to write to file: " << csvFile << "\n"; } } return 0; } The example `logfile.csv` looks like this after two runs: "header1","header2","header3" "1","Hallo","3.5" "2","Hallo","7" "3","Hallo","10.5" "4","Hallo","14" "5","Hallo","17.5" "6","Hallo","21" "7","Hallo","24.5" "8","Hallo","28" "9","Hallo","31.5" "1","Hallo","3.5" "2","Hallo","7" "3","Hallo","10.5" "4","Hallo","14" "5","Hallo","17.5" "6","Hallo","21" "7","Hallo","24.5" "8","Hallo","28" "9","Hallo","31.5" "1","Hallo","3.5" "2","Hallo","7" "3","Hallo","10.5" "4","Hallo","14" "5","Hallo","17.5" "6","Hallo","21" "7","Hallo","24.5" "8","Hallo","28" "9","Hallo","31.5" ### Possible improvements * Use a `struct` with the column data (making the amount of columns expandable) * Check if the folder exists * Check if the file exists but is empty (then write the header) * Checking and escaping special characters (like `"` or newlines) [1]: https://raymii.org/s/snippets/Cpp_create_and_write_to_a_CSV_file_with_a_variadic_template.html --- License: All the text on this website is free as in freedom unless stated otherwise. This means you can use it in any way you want, you can copy it, change it the way you like and republish it, as long as you release the (modified) content under the same license to give others the same freedoms you've got and place my name and a link to this site with the article as source. This site uses Google Analytics for statistics and Google Adwords for advertisements. You are tracked and Google knows everything about you. Use an adblocker like ublock-origin if you don't want it. All the code on this website is licensed under the GNU GPL v3 license unless already licensed under a license which does not allows this form of licensing or if another license is stated on that page / in that software: This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see . Just to be clear, the information on this website is for meant for educational purposes and you use it at your own risk. I do not take responsibility if you screw something up. Use common sense, do not 'rm -rf /' as root for example. If you have any questions then do not hesitate to contact me. See https://raymii.org/s/static/About.html for details.