First function: calculate the number of substrings in a string.
Int strstr_cnt (const char * string, const char * substring ){
Int I, J, K, Count = 0;
For (I = 0; string [I]; I ++ ){
For (j = I, K = 0; (string [J] = substring [k] & (j <strlen (string); j ++, k ++ ){
If (! Substring [k + 1]) {
Count ++;
}
}
}
Return count;
}
Second function: Calculate the position of a substring in the string.
Int substring_index (const char * S1, const char * S2, int POS ){
Int I, J, K;
For (I = Pos; S1 [I]; I ++ ){
For (j = I, K = 0; S1 [J] = S2 [k]; j ++, K ++ ){
If (! S2 [k + 1]) {
Return I;
}
}
}
Return-1;
}
Function 3: Read a row of a opened CSV file and process the row into an array.
Char * fgetcsvline (vector <string> & csv_databuf, file * fhead ){
Char * ret_stat;
Char data_buf [1024];
String stringbuf;
Ret_stat = fgets (data_buf, 1024, fhead );
If (ret_stat! = NULL ){
Int Len = strstr_cnt (data_buf ,"\",\"");
If (LEN> 0 ){
Int Pos = substring_index (data_buf, "\", \ "", 0 );
Int startpos = 1;
String csv_buf;
While (Pos> 0 ){
Stringbuf = (string) data_buf;
Csv_buf = stringbuf. substr (startpos, pos-startpos );
Csv_databuf.push_back (csv_buf );
Startpos = POS + 3;
Pos = substring_index (data_buf, "\", \ "", POS + 2 );
}
If (substring_index (data_buf, "\ n", 0)> 0 ){
Csv_buf = stringbuf. substr (startpos, stringbuf. Length ()-startpos-2 );
} Else {
Csv_buf = stringbuf. substr (startpos, stringbuf. Length ()-startpos-1 );
}
Csv_databuf.push_back (csv_buf );
}
}
Return ret_stat;
}
This function uses the above two functions to process strings.
In addition, the CSV file to be processed by this function is in double quotation marks format:
"Sss", "DDD", "444"
"TTT", "www", "ooo"
"Sss", "qqq", "000"
The usage is as follows:
Int main (INT argc, char * argv []) {
File * fp_head;
String csvfilename = "test.csv ";
Char * ret_stat;
Vector <string> csv_data;
Fp_head = fopen (csvfilename, "RT ");
Ret_stat = fgetcsvline (csv_data,
Fp_head );
While (ret_stat! = NULL ){
// Get CSV data use csv_data [N]
Ret_stat
= Fgetcsvline (csv_data, fp_head );
}
Return 0;
}
The above code may require a little debugging.
You can also slightly modify it to read CSV files in other formats.