none
How to write into a csv file in C?

    Question

  •  Hi!
    I am a little new to programming and I want to now how I can write into a csv file in C?
    I need the command with some examples showing how this coud be implemented.

    Thanks.

    Regards,Yashar
    Monday, February 02, 2009 12:14 PM

Answers


  • #include <stdio.h> 
     
    struct MyData { 
      int someValue; 
      char const *someString; 
      float someSample; 
    }; 
     
    int write_to_file(int count, struct MyData *data, char const *fileName) 
      FILE *f = fopen(fileName, "w"); 
      if (f == NULL) return -1; 
      while (count-- > 0) { 
        // you might want to check for out-of-disk-space here, too 
        fprintf(f, "%d,%s,%f\n", data->someValue, data->someString, data->someSample); 
        ++data; 
      } 
      fclose(f); 
      return 0; 
     


    Note that this does not properly handle strings with embedded '"' or ',' characters. To do that, you need to quote the input string properly into a temporary buffer, and then pass that temporary buffer for the string argument.


    XNA/DirectX MVP 2006-present
    Wednesday, February 04, 2009 12:31 AM
  • yade:

    IMHO, a more natural approach is to make count the number of elements and write

    int write_to_file(int count, struct MyData const *data, char const *fileName)
    {
      FILE *f=fopen(fileName,"w");
      if(f==NULL) return -1;
      for (int i=0; i<count; i++)
      {
        fprintf(f,"%d,%s,%f\n",data[i].SomeString, data[i].SomeValue, data[i].SomeSample);
      }
      fclose(f);
      return 0;
    }


    In your example you would call this function with count = 1.

    David Wilkinson | Visual C++ MVP
    Wednesday, February 04, 2009 2:02 PM

All replies

  • Via Google I found a csv library on sourceforge:

    http://sourceforge.net/projects/libcsv/

    Download it and have a look through the source code.


    But the general principle to write a csv file is as follow:

    Open file

    for each row r
        for each field f in row r

              For the field value replace " with ""
              Write " + value + "

              if not last field in row
                  Write ","
             end if

       end for

       Write "\n"
    end for

    Close file

    Thanks

    Monday, February 02, 2009 12:49 PM
  • It's often easier to see the past than the future:


    for each row r
        for each field f in row r

              if not first field in row
                  Write ","
             end if


              For the field value replace " with ""
              Write " + value + "

       end for

       Write "\n"
    end for
    Monday, February 02, 2009 2:35 PM
  • There are very many ways to do it. Anyone with beginner-level experience with C++ can create a way to do it. You won't always get people willing to do it all for you. It will benefit you to get a book about C++.

    I don't know if you meant C++ when you said C; I hope you did. It would be more beneficial to learn C++ first.

    Sam Hobbs; see my SimpleSamples.Info
    Monday, February 02, 2009 5:18 PM
  • Ok thanks!
    To Simple Samples:
    I couldn't find the topic in a book. If you have a good reference, i'd like to know that.

    No, I need it to be done in C not C++. I should collect some data from the C witten program
    and transfer it into another program . I thought of writing to a csv file as agood way for this purpose.
    Can  I do that with fopen/fwrite/fclose ?
    Tuesday, February 03, 2009 9:50 AM
  • Yes, fopen/fwrite/fclose will do.

    C Tutorial here.
    Tuesday, February 03, 2009 5:02 PM

  • #include <stdio.h> 
     
    struct MyData { 
      int someValue; 
      char const *someString; 
      float someSample; 
    }; 
     
    int write_to_file(int count, struct MyData *data, char const *fileName) 
      FILE *f = fopen(fileName, "w"); 
      if (f == NULL) return -1; 
      while (count-- > 0) { 
        // you might want to check for out-of-disk-space here, too 
        fprintf(f, "%d,%s,%f\n", data->someValue, data->someString, data->someSample); 
        ++data; 
      } 
      fclose(f); 
      return 0; 
     


    Note that this does not properly handle strings with embedded '"' or ',' characters. To do that, you need to quote the input string properly into a temporary buffer, and then pass that temporary buffer for the string argument.


    XNA/DirectX MVP 2006-present
    Wednesday, February 04, 2009 12:31 AM
  • Hi!
    Thanks Jon Watte. The sample code was so useful.
    However, I have a debugging problem and nothing gets saved in CSV file. What is THAT for?

    Here is the error :

    Unhandled exception at 0x6507984f (msvcr90d.dll) in CSVTestProg.exe: 0xC0000005:
    Access violation reading location 0xcccccccc.


    Break                  Continue   

    And the code :

    #include <stdio.h>
    #include <stdlib.h>
    #include "Test.h"


    struct MyData{
    char const *SomeString;
    int SomeValue;
    float SomeSample;
    };

    int write_to_file(int count, struct MyData *data, char const *fileName)
    {
    FILE *f=fopen(fileName,"w");
    if(f==NULL) return -1;
    while(count-- >0){
        fprintf(f,"%s = %d  %f\n",data->SomeString,data->SomeValue,data->SomeSample);
        ++data;
    }
    fclose(f);
    return 0;
    }

    int main()
    {
    MyData Test1;
    Test1.SomeString="IR_Source 1";
    Test1.SomeValue=10;
    Test1.SomeSample=55.5;
    write_to_file(2,&Test1,"Results");
     return 0;
    }


    Test.h

    int write_to_file(int count, struct MyData *data, char const *fileName);




    Wednesday, February 04, 2009 9:15 AM
  • OK! Now it seems that the program is working and I get some data saved in csv file, although I don't know exactly what the problem was.

    can you tell me what are you using the varalbe count for?!
    And what does data ++ do?

    Wednesday, February 04, 2009 11:29 AM
  • Hi,

    what are u trying to do with ++data. U cannot do a ++data here. U have taken the address of Test1 and one unit and u are trying to do out of that and access the location 0xCCCCCCCC, which is not there. remove ++data.


    MFC
    Wednesday, February 04, 2009 11:53 AM
  • Ok! what should be replace instead of struct MyData *data in the function ?
    Wednesday, February 04, 2009 12:15 PM
  • Which ever u are passing from the main function to write function as a second parameter that should be an array with count size. like if count is 10 then ur array size should also be ten.
    MFC
    Wednesday, February 04, 2009 12:49 PM
  • yade:

    IMHO, a more natural approach is to make count the number of elements and write

    int write_to_file(int count, struct MyData const *data, char const *fileName)
    {
      FILE *f=fopen(fileName,"w");
      if(f==NULL) return -1;
      for (int i=0; i<count; i++)
      {
        fprintf(f,"%d,%s,%f\n",data[i].SomeString, data[i].SomeValue, data[i].SomeSample);
      }
      fclose(f);
      return 0;
    }


    In your example you would call this function with count = 1.

    David Wilkinson | Visual C++ MVP
    Wednesday, February 04, 2009 2:02 PM
  • write_to_file(2,&Test1,"Results");

     

    "count" is the number of records in your array. Because "Test1" is only a single record, you need to pass "1" for count.

     


    XNA/DirectX MVP 2006-present
    Wednesday, February 04, 2009 7:21 PM
  • from the chip . and program i am getting the folder with the data written in CSV ,which contain 401 rows like this 

    1------------------

    2----------

    3---------

    upto

    401---------------

     

    I just want 401th row only .how can i do this ?

     

     

    Tuesday, July 05, 2011 7:42 PM
  • SurajSahu, your question is a different question. Please create a new thread for your question.

    Sam Hobbs
    SimpleSamples.Info
    Tuesday, July 05, 2011 11:02 PM