CSV is a simple file format used to store tabular data such as a spreadsheet or a database. CSV stands for Comma Separated Values. The data fields in a CSV file are separated/delimited by a comma (‘, ‘) and the individual rows are separated by a newline (‘\n’). CSV File management in C++ is similar to text-type file management, except for a few modifications.
This article discusses about how to create, update and delete records in a CSV file:
Note: Here, a reportcard.csv file has been created to store the student’s roll number, name and marks in math, physics, chemistry and biology.
- Create operation:
The create operation is similar to creating a text file, i.e. input data from the user and write it to the csv file using the file pointer and appropriate delimiters(‘, ‘) between different columns and ‘\n’ after the end of each row.
CREATE
voidcreate(){// file pointerfstream fout;// opens an existing csv file or creates a new file.fout.open("reportcard.csv", ios::out | ios::app);cout <<"Enter the details of 5 students:"<<" roll name maths phy chem bio";<< endl;inti, roll, phy, chem, math, bio;string name;// Read the inputfor(i = 0; i < 5; i++) {cin >> roll>> name>> math>> phy>> chem>> bio;// Insert the data to filefout << roll <<", "<< name <<", "<< math <<", "<< phy <<", "<< chem <<", "<< bio<<"\n";}}chevron_rightfilter_noneOutput:

- Read a particular record:
In reading a CSV file, the following approach is implemented:-
- Using getline(), file pointer and ‘\n’ as the delimiter, read an entire row and store it in a string variable.
- Using stringstream, separate the row into words.
- Now using getline(), the stringstream pointer and ‘, ‘ as the delimiter, read every word in the row, store it in a string variable and push that variable to a string vector.
- Retrieve a required column data through row[index]. Here, row[0] always stores the roll number of a student, so compare row[0] with the roll number input by the user, and if it matches, display the details of the student and break from the loop.
Note: Here, since whatever data reading from the file, is stored in string format, so always convert string to the required datatype before comparing or calculating, etc.
READ
voidread_record(){// File pointerfstream fin;// Open an existing filefin.open("reportcard.csv", ios::in);// Get the roll number// of which the data is requiredintrollnum, roll2, count = 0;cout <<"Enter the roll number "<<"of the student to display details: ";cin >> rollnum;// Read the Data from the file// as String Vectorvector<string> row;string line, word, temp;while(fin >> temp) {row.clear();// read an entire row and// store it in a string variable 'line'getline(fin, line);// used for breaking wordsstringstream s(line);// read every column data of a row and// store it in a string variable, 'word'while(getline(s, word,', ')) {// add all the column data// of a row to a vectorrow.push_back(word);}// convert string to integer for comparisionroll2 = stoi(row[0]);// Compare the roll numberif(roll2 == rollnum) {// Print the found datacount = 1;cout <<"Details of Roll "<< row[0] <<" : \n";cout <<"Name: "<< row[1] <<"\n";cout <<"Maths: "<< row[2] <<"\n";cout <<"Physics: "<< row[3] <<"\n";cout <<"Chemistry: "<< row[4] <<"\n";cout <<"Biology: "<< row[5] <<"\n";break;}}if(count == 0)cout <<"Record not found\n";}chevron_rightfilter_noneOutput:

- Update a record:
The following approach is implemented while updating a record:-
- Read data from a file and compare it with the user input, as explained under read operation.
- Ask the user to enter new values for the record to be updated.
- update row[index] with the new data. Here, index refers to the required column field that is to be updated.
- Write the updated record and all other records into a new file(‘reportcardnew.csv’).
- At the end of operation, remove the old file and rename the new file, with the old file name, i.e. remove ‘reportcard.csv’ and rename ‘reportcardnew.csv’ with ‘reportcard.csv’
UPDATE
voidupdate_recode(){// File pointerfstream fin, fout;// Open an existing recordfin.open("reportcard.csv", ios::in);// Create a new file to store updated datafout.open("reportcardnew.csv", ios::out);introllnum, roll1, marks, count = 0, i;charsub;intindex, new_marks;string line, word;vector<string> row;// Get the roll number from the usercout <<"Enter the roll number "<<"of the record to be updated: ";cin >> rollnum;// Get the data to be updatedcout <<"Enter the subject "<<"to be updated(M/P/C/B): ";cin >> sub;// Determine the index of the subject// where Maths has index 2,// Physics has index 3, and so onif(sub =='m'|| sub =='M')index = 2;elseif(sub =='p'|| sub =='P')index = 3;elseif(sub =='c'|| sub =='C')index = 4;elseif(sub =='b'|| sub =='B')index = 5;else{cout <<"Wrong choice.Enter again\n";update_record();}// Get the new markscout <<"Enter new marks: ";cin >> new_marks;// Traverse the filewhile(!fin.eof()) {row.clear();getline(fin, line);stringstream s(line);while(getline(s, word,', ')) {row.push_back(word);}roll1 = stoi(row[0]);introw_size = row.size();if(roll1 == rollnum) {count = 1;stringstream convert;// sending a number as a stream into output stringconvert << new_marks;// the str() converts number into stringrow[index] = convert.str();if(!fin.eof()) {for(i = 0; i < row_size - 1; i++) {// write the updated data// into a new file 'reportcardnew.csv'// using foutfout << row[i] <<", ";}fout << row[row_size - 1] <<"\n";}}else{if(!fin.eof()) {for(i = 0; i < row_size - 1; i++) {// writing other existing records// into the new file using fout.fout << row[i] <<", ";}// the last column data ends with a '\n'fout << row[row_size - 1] <<"\n";}}if(fin.eof())break;}if(count == 0)cout <<"Record not found\n";fin.close();fout.close();// removing the existing fileremove("reportcard.csv");// renaming the updated file with the existing file namerename("reportcardnew.csv","reportcard.csv");}chevron_rightfilter_noneOutput:

- Delete a record:
The following approach is implemented while deleting a record
- Read data from a file and compare it with the user input, as explained under read and update operation.
- Write all the updated records, except the data to be deleted, onto a new file(reportcardnew.csv).
- Remove the old file, and rename the new file, with the old file’s name.
DELETE
voiddelete_record(){// Open FIle pointersfstream fin, fout;// Open the existing filefin.open("reportcard.csv", ios::in);// Create a new file to store the non-deleted datafout.open("reportcardnew.csv", ios::out);introllnum, roll1, marks, count = 0, i;charsub;intindex, new_marks;string line, word;vector<string> row;// Get the roll number// to decide the data to be deletedcout <<"Enter the roll number "<<"of the record to be deleted: ";cin >> rollnum;// Check if this record exists// If exists, leave it and// add all other data to the new filewhile(!fin.eof()) {row.clear();getline(fin, line);stringstream s(line);while(getline(s, word,', ')) {row.push_back(word);}introw_size = row.size();roll1 = stoi(row[0]);// writing all records,// except the record to be deleted,// into the new file 'reportcardnew.csv'// using fout pointerif(roll1 != rollnum) {if(!fin.eof()) {for(i = 0; i < row_size - 1; i++) {fout << row[i] <<", ";}fout << row[row_size - 1] <<"\n";}}else{count = 1;}if(fin.eof())break;}if(count == 1)cout <<"Record deleted\n";elsecout <<"Record not found\n";// Close the pointersfin.close();fout.close();// removing the existing fileremove("reportcard.csv");// renaming the new file with the existing file namerename("reportcardnew.csv","reportcard.csv");}chevron_rightfilter_noneOutput:

References: https://www.geeksforgeeks.org/file-handling-c-classes/, https://www.geeksforgeeks.org/stringstream-c-applications/
Rated as one of the most sought after skills in the industry, own the basics of coding with our C++ STL Course and master the very concepts by intense problem-solving.
Recommended Posts:
- C program to copy contents of one file to another file
- Implementation of all Partition Allocation Methods in Memory Management
- Print "Hello World" in C/C++ without using any header file
- Understanding ShellExecute function and it's application to open a list of URLs present in a file using C++ code
- Convert byte[] array to File using Java
- Read a record from a File in C++ using seekg() and tellg()
- Implementation of file allocation methods using vectors
- C++ File Writer-Reader application using Windows Threads
- fopen() for an existing file in write mode
- Implement your own tail (Read last n lines of a huge file)
- Four File Handling Hacks which every C/C++ Programmer should know
- lseek() in C/C++ to read the alternate nth byte and write it in another file
- Write a C program that displays contents of a given file like 'more' utility in Linux
- C Program to count number of lines in a file
- C Program to print contents of file
- C Program to merge contents of two files into a third file
- C program to delete a file
- C++ program to print unique words in a file
- Read/Write Class Objects from/to File in C++
- Find sum of integers in a file which contains any characters
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.
Improved By : nidhi_biet

