Thread: Read data from a .csv file in c

  1. #1
    Registered User
    Join Date
    Nov 2020
    Posts
    31

    Read data from a .csv file in c

    Hello, I have written a small C programm where I can read data in from a .csv file. This works fine.

    But now I want to create a function to read the data in. So I want modify my programm.

    I have tried to put the fopen() in a function and to return this value. But this not works.

    Here is my original program:

    Code:
    #include <stdio.h>
    #include <stdlib.h>
    #include <math.h>
    
    
    
    int main(void)
    {
    
        FILE *fp;
    
        fp = fopen("data.csv","r");
    
        if (fp == NULL)
        {
            printf("Can not open file");
            exit(0);
        }
    
        char line[100];
        char *sp;
        double acceleration;
        double rotation;
        double temperature;
        double totalTemperature;
        int count = 0;
    
    
        double direction=0;
    
        while(fgets(line, 100, fp )!= NULL)
        {
            sp = strtok(line, ",");
            acceleration = atof(sp);
    
            sp = strtok(NULL, ",");
            rotation = atof(sp);
    
            sp = strtok(NULL, ",");
            temperature = atof(sp);
    
            totalTemperature += temperature;
            count++;
    
    
        }
    
        printf("The mean Temperature is: %.14f\n", totalTemperature/count);
    
        fclose(fp);
    
        return 0;
    
    }

    As I said I want to create a function named read_data(), i want to modify my orignal program. This function should read the data from the .csv file, but I did not know what the return should be look like.

    I have tried something like that, but it did not worked:

    Code:
    char * read_data(char* filename)
    {
    
        FILE *fp;
    
        fp = fopen("data.csv","r");
    
        if (fp == NULL)
        {
            printf("Can not open file");
            exit(0);
        }
    
        fclose(fp);
    
        return fp;
    
    
    }
    Thanks for a help.

  2. #2
    Registered User
    Join Date
    Feb 2019
    Posts
    1,078
    Rfc 4180

  3. #3
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    39,661
    > but I did not know what the return should be look like.
    Well your existing loop throws away nearly all that is read.

    So what do you want to do really?

    At a very basic level, you could store just the fields as character strings.
    Code:
    struct row {
        char field[5][20];  // 5 fields, up to 20 chars
    };
    Or you could parse the data, and end up with
    Code:
    struct row {
        double acceleration;
        double rotation;
        double temperature;
    };
    In either case, you could implement something like this to read each row in turn
    Code:
    struct row read_next_row(FILE *fp) {
        char line[100];
        if (fgets(line, 100, fp )!= NULL) {
        }
    }
    Or you could read the entire file
    Code:
    void read_file(struct row rows[], size_t maxRows, FILE *fp)
    It really boils down to what you want to store, and how long you want to store it for.
    If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
    If at first you don't succeed, try writing your phone number on the exam paper.

  4. #4
    Registered User
    Join Date
    Nov 2020
    Posts
    31
    Ok Thanks for the help. I have now tried another approach. I am able to read the data in with the written function read_data().

    Code:
    #include <stdio.h>
    #include <stdlib.h>
    #include <math.h>
    
    
    
    
    char* read_file(char* filename)
    {
        FILE *fptr;
    
        if ((fptr = fopen(filename,"r")) == NULL){
            printf("Error! opening file");
            exit(1);
        }
    
        fseek(fptr, 0, SEEK_END);
        long size = ftell(fptr);
        fseek(fptr, 0, SEEK_SET);
    
        char* fcontent = (char*)calloc(size, sizeof(char));
    
        fread(fcontent, 1, size, fptr);
    
        fclose(fptr);
    
        return fcontent;
    }
    
    
    
    
    
    int main(void)
    {
    
    
        char* fp = read_file("data.csv");
    
        printf("%s",fp);
    
        char line[100];
        char *sp;
        double acceleration;
        double rotation;
        double temperature;
        double totalTemperature;
        int count = 0;
    
        while(fgets(line, 100, fp )!= NULL)
        {
            sp = strtok(line, ",");
            acceleration = atof(sp);
    
            sp = strtok(NULL, ",");
            rotation = atof(sp);
    
            sp = strtok(NULL, ",");
            temperature = atof(sp);
    
            totalTemperature += temperature;
            count++;
    
    
        }
    
        printf("The mean Temperature is: %.14f\n", totalTemperature/count);
    
        return 0;
    
    }
    But now the mean temperature can not be calculated. In my first program that was possible. I did not know what is wrong, because after calling the function read_data() I am able to plot the data from the main function. But the following while loop has now problems to evaluate the data. Thanks for a hint.

  5. #5
    Registered User
    Join Date
    May 2010
    Posts
    4,632
    The code you posted should not compile, as there are several errors.

    You really should read the documentation for the standard functions you are trying to use. For example fgets() expects a FILE pointer for the third argument, not a char pointer. And you need to insure that you #include all the required headers, string.h in this case is required.

    Be careful with fseek() when being used with a text stream (from Microsoft documentation of fseek()):

    For streams opened in text mode, fseek and _fseeki64 have limited use, because carriage return-line feed translations can cause fseek and _fseeki64 to produce unexpected results. The only fseek and _fseeki64 operations guaranteed to work on streams opened in text mode are:

    Seeking with an offset of 0 relative to any of the origin values.

    Seeking from the beginning of the file with an offset value returned from a call to ftell when using fseek or _ftelli64 when using _fseeki64.

  6. #6
    Registered User
    Join Date
    Nov 2020
    Posts
    31
    Thanks for the help now it works:

    Code:
    #include <stdio.h>
    #include <stdlib.h>
    #include <math.h>
    #include <string.h>
    
    FILE *read_file(char* filename)
    {
        FILE *fptr;
    
        if ((fptr = fopen(filename,"r")) == NULL)
        {
            printf("Error! opening file");
            exit(1);
        }
    
        return fptr;
    }
    
    
    
    int main(void)
    {
        FILE *fp = read_file("data.csv");
    
        char line[100];
        char *sp;
        double acceleration;
        double rotation;
        double temperature;
        double totalTemperature;
        int count = 0;
    
        double direction=0;
    
        while(fgets(line, 100, fp )!= NULL)
        {
            sp = strtok(line, ",");
            acceleration = atof(sp);
    
            sp = strtok(NULL, ",");
            rotation = atof(sp);
    
            sp = strtok(NULL, ",");
            temperature = atof(sp);
    
            totalTemperature += temperature;
            count++;
    
        }
    
    
        printf("The mean Temperature is: %.14f %cC\n", totalTemperature/count, (char)248);
    
        return 0;
    
    }

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Read Input file, Calculate data, Write Output file
    By Ron09sime in forum C Programming
    Replies: 10
    Last Post: 07-04-2021, 02:17 AM
  2. Replies: 3
    Last Post: 03-13-2013, 07:10 PM
  3. Replies: 21
    Last Post: 11-03-2007, 02:56 PM
  4. how do i read data from a file?
    By ssjnamek in forum C++ Programming
    Replies: 19
    Last Post: 02-01-2002, 04:58 PM

Tags for this Thread