In C programming, using arrays and string for data storage at run time which is volatile and gets memory in RAM. But to store data permanently in a hard disk which can be manipulated furthermore. So, the idea is to use a CSV file for data storage and manipulation. Not only CSV but other files like dat, txt, and bin can also be used for data manipulation. But CSV file as the name suggests (Comma Separated Values) stores data in a table format which saves a lot of time in making perfect structure.
In Relational Databases data gets stored in a table format so by using CSV File, the database can be created.
Below is an example of a CSV File:
For concepts of File Handling, refer to the Basic File Handling in C article.
Create a buffer of character array (can be referred to as string) which takes all the data present in the file and by using File Pointer and fgets() data can be extracted. Use two variables row and column which will maintain the unique identification of every entry.
As the string contains comma ‘, ‘ for separating values, so the idea is to use strtok() function for splitting values. This function splits a string using a delimiter here we are using ‘, ‘.
Data Extraction deals with Opening an existing CSV file and extracting and printing the whole data on the console.
- Open CSV File using File Pointer.
- Extract the whole file data into a char buffer array.
- Now initialize row and column variables with value 0.
- Print data separated by a comma and increase the column variable.
- When reached to the end of a row entry initialize column variable to 0 and increase row variable.
- Repeat steps 4 and 5, till the pointer reaches the end of the file.
- Close the file.
Below is the program for the same:
Data Addition deals with opening an existing CSV file, taking user inputs for the data to be added to the file, and then adding this data to the CSV file.
- Open CSV File using File Pointer in append mode which will place a pointer to the end of the file.
- Take Input from the user in temporary variables.
- Use fprintf() and separate variables according to their order and comma.
- Close the file.
Advantages Of CSV File:
- Different from .txt and .dat file in terms of storing data in table format.
- Easy to organize data by direct user interaction or by the program.
- Widely adopted in financial industries to store and transmit data over the internet.
- Easily converted to other files and formats.
- It can be imported or exported to various platforms and interfaces.