CSV files or Comma Separated Value Files are simple yet special files that we use to store data. Here, each value is separated by a comma, and each line is limited by a newline character. We use CSV files to store tabular data. It helps us in recognizing different column values by separating them by comma and we can recognize the rows by a newline. In this article, we will see how we can read a CSV file in C++. We will discuss ways to read CSV files line by line and then extract the column values from each line.
Table of Contents
What is a CSV File?
The sample CSV file looks like the one given below.
1 2 3 4 5 6 |
name,gender,age abc,male,21 xyz,female,18 pqr,male,19 |
In this file, each of the values in each line is separated by a comma. The first row represents column names that are name, gender, and age respectively. After each line, there is a newline character that is stored internally and not visible in the file. Each row in the file represents a different record while each comma-separated value represents a field of the record.
How To Read A CSV File In C++?
Reading the CSV file is essentially similar to reading all other files in C++. The difference lies in the way the values are extracted from the lines. To read a CSV file,
- We will open the file using ‘
fstream
’ or ‘ifstream
’ C++ library. Then, we will read the file line by line using thegetline()
method as each line ends with a newline character. - The
getline()
method takes a file stream as its first input argument and a string variable as its second argument. After execution, it stores the next line of the file stream in the string variable. It also accepts an optional argumentdelimitor
. If we pass a delimiter as the input argument, it reads the file till the delimiter is found. Otherwise, it reads the file till the newline character is found. - After extracting a line, we will use
stringstream
to extract the words that are separated in the line by a comma. As the name suggests,stringstream
converts a string to a file stream-like object. - Here, we will use the
getline()
method to read the string stream object created bystringstream
. While usinggetline()
, apart from the string stream and a string variable named ‘word
’, we also pass “,
” as the third argument to thegetline()
function. In this way, thegetline()
function reads the data only till the nextcomma
sign in a single line. - We store each word in a vector named
row
and Eachrow
is stored in a 2-D vector namedcontent
. After execution of the entire program, we get a 2-d vector where each row represents a record in the CSV file and each column of each row represents the data in it.
C++ Code To Read A CSV File
Using the approach discussed above, we have implemented the code to read a CSV file in C++.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 |
#include <iostream> #include <fstream> #include <string> #include <vector> #include <sstream> using namespace std; int main() { string fname; cout<<"Enter the file name: "; cin>>fname; vector<vector<string>> content; vector<string> row; string line, word; fstream file (fname, ios::in); if(file.is_open()) { while(getline(file, line)) { row.clear(); stringstream str(line); while(getline(str, word, ',')) row.push_back(word); content.push_back(row); } } else cout<<"Could not open the file\n"; for(int i=0;i<content.size();i++) { for(int j=0;j<content[i].size();j++) { cout<<content[i][j]<<" "; } cout<<"\n"; } return 0; } |
The output of the above code is given below. We have used the CSV file given above as the input to the program.
1 2 3 4 5 6 7 8 |
Enter the file name: sample.csv name gender age abc male 21 xyz female 18 pqr male 19 |
Further reading:
How To Read A CSV File Using C-Based Approach?
Reading the CSV file in C is fundamentally similar to reading a CSV file in C++. However, we will use a different approach to read the content and display the file on the console output. The steps are given as follows.
- First, we will open the file using the
fopen()
function. Thefopen()
function accepts the file name as its first argument and read/write mode as its second argument. Here, we will use the read mode to open the file. - We will also create a character array to keep the contents of the file. The size of the array can be decided accordingly.
- To read the content from the file into the array, we will use the
fgets()
function. Thefgets()
function takes a character array as its first argument, the size of the content to be read as the second argument, and the file pointer as its third argument. After execution, it stores the content read from the file into the character array. - After storing the content of the file in a character array, we will use the
strtok()
function to separate the words usingcomma
as the separator. Thestrtok()
function takes the string as its first input argument and the separator as its second input argument.To search for tokens, the first character is utilized as a starting point when thestrtok()
function is executed for the first time. The function expects aNULL
pointer on subsequent calls and it starts from the right of the end of the last token as the new starting location for scanning. After each scan, it return a token i.e. substring between the separators. Once the entire string is scanned, it returns aNULL
value. - We will read the file line by line using the
fgets()
function and will tokenize each comma-separated value using thestrtok()
function as shown below.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 |
#include <stdio.h> #include <string.h> int main() { char fname[1024]; printf("Enter the file name: "); scanf ("%s", fname); FILE *file = fopen(fname, "r"); if(!file) { printf("Could not open the file\n"); return 0; } char content[1024]; while(fgets(content, 1024, file)) { char *v = strtok(content, ","); while(v) { printf("%s ", v); v = strtok(NULL, ","); } printf("\n"); } fclose(file); return 0; } |
Output:
1 2 3 4 5 6 7 8 9 10 |
Enter the file name: sample.txt name gender age abc male 21 xyz female 18 pqr male 19 |
In the above code, when the strtok()
function is executed for the first time, it returns the string till the first comma. On each subsequent execution, it returns the string till the next comma
.
Conclusion
Comma Separated Value (CSV) files are used to store tabular data. C++ does not have any inbuilt library to read CSV files directly. However, we can read them like any other file. The files are read line by line and then separated by commas to get each word. In this way, we can read the files in exactly the same way as it is stored in the original spreadsheet or database.
Although C also does not have any built-in library to read the CSV files, we can read the file using file pointers and then read it in the same way as any other file. To get each value, we separate the values by a comma. This is an elegant way to read the values from CSV files which can be used to process the data for further necessities. You can choose any method to read CSV files according to your convenience.
I hope you enjoyed reading this article. Stay tuned for more informative articles.
Happy Learning!