Link to home
Create AccountLog in
Editors IDEs

Editors IDEs

--

Questions

--

Followers

Top Experts

Avatar of thomasbonham
thomasbonham🇺🇸

Read a CSV in C
What is the best way to read a csv file in C (not  C# or C++ just C)? I tried using strtok and that works but it split stuff that shoudn't be split up.

Thanks for the help.

Thomas

Zero AI Policy

We believe in human intelligence. Our moderation policy strictly prohibits the use of LLM content in our Q&A threads.


Avatar of AxterAxter🇺🇸

Please post your code, and specify exactly what it splits that shouldn't be split.

Avatar of Infinity08Infinity08🇧🇪

Something like this :

    char line[MAX_LINE_LENGTH] = { 0 };
    FILE *csvFile = fopen("test.csv", "r");
    int cnt = 0;
    if (csvFile) {
        char *token = 0;
        while (fgets(line, MAX_LINE_LENGTH, csvFile)) {
            printf("line %d : ", cnt++);
            token = strtok(line, ";");
            while (token) {
                printf("%s\t", token);
                token = strtok(NULL, ";");
            }
            printf("\n");
        }
        fclose (csvFile);
    }

Avatar of AxterAxter🇺🇸

Please specify exactly what it splits that shouldn't be split.

Reward 1Reward 2Reward 3Reward 4Reward 5Reward 6

EARN REWARDS FOR ASKING, ANSWERING, AND MORE.

Earn free swag for participating on the platform.


Avatar of Anthony2000Anthony2000🇺🇸

I think the best way to read the file is to simply write your own function to break up the tokens. This is because strtok will not be able to tell the difference between a "," that is meant to separate a field versus a "," that is embedded in a string.
i.e. potential CSV file:

Name, address,telehone number
Tom, "New York, NY",212-234-2345
John,"Irvine, CA",904-123-0987

of course I am making the assumption that your CSV file contains strings with "" around them and that they may contain embedded ",".

Otherwise Infinity08's code looks good and should work.

If you have some control on how the CSV file is created, use tabs as separators and then in Infinity08's code change the strtok to use "\t" instead of ",". I believe that should work also.

Avatar of thomasbonhamthomasbonham🇺🇸

ASKER

I don't have any code right now to post that is what I'm trying to work on. As for the data that shouldn't be split here is a example of it.

Example:

"Door of files, item tag in the back"

Anthony2000 would I go about doing this. I'm still some what new to C so I don't know how to do alot of the thing that I need to do for stuff like that.

Thank you,

Thomas

Avatar of Infinity08Infinity08🇧🇪

>> "Door of files, item tag in the back"

Use a different separator when generating the .csv file (choose one that is not present in any of the fields, like a ; or a tab) - that's the only way to make sure that the data read splits the fields up in the correct locations.

Free T-shirt

Get a FREE t-shirt when you ask your first question.

We believe in human intelligence. Our moderation policy strictly prohibits the use of LLM content in our Q&A threads.


Avatar of thomasbonhamthomasbonham🇺🇸

ASKER

>> Use a different separator when generating the .csv file (choose one that is not present in any of the    
>> fields, like a ; or a tab) - that's the only way to make sure that the data read splits the fields up in the
>> correct locations.
 
I wish I could do that but I don't have the chose of doing that. I don't have any thing to do with create the file I just have to do the splitting of it and the importing of it.

Thomas

Avatar of Infinity08Infinity08🇧🇪

>> I wish I could do that but I don't have the chose of doing that. I don't have any thing to do with create the file I just have to do the splitting of it and the importing of it.

Well, then you have a problem, because the file was generated incorrectly.

How can you know how to split this line eg. :

      some text, and some more, and here's another line, with something extra, and a bit more

I tell you that there are 3 fields in there - but you have no idea of knowing where to split.

If the file would have been generated like this :

      some text, and some more; and here's another line, with something extra; and a bit more

there is no problem, and you can easily split up at the ; borders.



So, in short : unless you have some way of determining which comma's are splitters, and which are part of the value, you're going to have to find a way to re-generate the .csv file.

Avatar of PaulCaswellPaulCaswell🇬🇧

This should work but I haven't tested it:

char * strtok2( char * str, char * seps ) {
  static char * s = null; // String I am working on.
  char * token = null;
  // Grab the new string if they gave me one.
  if ( str != null ) s = str;
  // Nothing more to deliver if s is exhausted.
  if ( s != null ) {
    int i;
    // Boolean for whether we are in quotes or not.
    int inQuotes = 0;
    for ( i = 0; s[i] != '\0' && token == null; i++ ) {
      switch ( s[i] ) {
         case '\"': inQuotes = true; break;
         default:
             if ( !inQuotes && strchr ( seps, s[i] ) != null ) {
                // Found a separator not in quotes!
                // Chop the string here.
                s[i] = '\0';
                // Allow the return of the token.
                token = s;
                // Skip the token for the next call.
                s = &s[i+1];
             }
             break;
      }
    }
  }

  return token;
}

I havent dealt with the special case where the quotes do not match.

Paul

Reward 1Reward 2Reward 3Reward 4Reward 5Reward 6

EARN REWARDS FOR ASKING, ANSWERING, AND MORE.

Earn free swag for participating on the platform.


Avatar of Infinity08Infinity08🇧🇪

Are there quotes around the fields, thomasbonham ? Can you give an example of a .csv file where your code doesn't work (just a few lines) ?

ASKER CERTIFIED SOLUTION
Avatar of Anthony2000Anthony2000🇺🇸

Link to home
membership
Log in or create a free account to see answer.
Signing up is free and takes 30 seconds. No credit card required.
Create Account

SOLUTION
Avatar of ozoozo🇺🇸

Link to home
membership
Log in or create a free account to see answer.
Signing up is free and takes 30 seconds. No credit card required.

SOLUTION
Avatar of PaulCaswellPaulCaswell🇬🇧

Link to home
membership
Log in or create a free account to see answer.
Signing up is free and takes 30 seconds. No credit card required.

Avatar of thomasbonhamthomasbonham🇺🇸

ASKER

I have it working now. Please give me a few days to post the code and the points.

Thanks
Editors IDEs

Editors IDEs

--

Questions

--

Followers

Top Experts

Development in most programming languages is frequently done with an editor or integrated development environment (IDE). An IDE is a software application that provide comprehensive facilities to computer programmers for software development. An IDE normally consists of a source code editor, build automation tools and a debugger. XCode, Visual Studio, Adobe Dreamweaver and Eclipse are some of the more popular development tools, but an editor or IDE can be anything from simple text editors to sophisticated programs. Related topics: All programming and development language, database and web based content management systems topics