Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations gkittelson on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Reading data from a CSV file

Status
Not open for further replies.

WernerSchwarz

Programmer
Jun 30, 2003
11
CH
I have to read out some data from a csv-file which is in this format:

[ID], [Timestamp] ,[Temp in °C]
[ID], [Timestamp] ,[Temp in °C]
etc.

now i wanted to read it out with the fscanf() function, but when i used it it just reads till the first space and then stops. How can i solve this problem?
 
I would use fgets() to read the file, then use sscanf() to parse the line from memory, rather than parse the file directly.

Code:
#include <stdio.h>

int main (void) {
    char buff[BUFSIZ];
    FILE *fp = fopen(&quot;file.csv&quot;,&quot;r&quot;);
    while ( fgets( buff, BUFSIZ, fp ) != NULL ) {
        /* Example - int fields */
        int id, timestamp, temperature;
        if ( sscanf( buff, &quot;%d,%d,%d&quot;, &id, &timestamp, &temperature ) != 3 ) {
            fprintf( stderr, &quot;Bad format: %s&quot;, buff );
        } else {
            /* do something */
        }
    }
    fclose(fp);
    return 0;
}

To parse a string, you would do this
Code:
    char id[100];
    int timestamp, temperature;
    if ( sscanf( buff, &quot;%99[^,],%d,%d&quot;, id, &timestamp, &temperature ) != 3 ) {
The 99 limits the amount of data to be written to your char array, and the [tt][^,][/tt] is a character class which matches all characters except comma. It's just like a regular %s conversion except you can specify which chars are valid for the string.


--
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top