I have a file with 190 lines, that goes something like this:

Antigua,English,Local dialects
Bahamas,English,Creole
Barbados,English
Belize,English,Spanish,Mayan,Carib
Canada,English,French
Costa Rica,Spanish,English
Cuba,Spanish

First field is the country, following fields are the different languages spoken in that country.
Since some countries have more languages than others, I am stuck trying to read the file using fgets() and sscanf().
I'm doing this:

while(i < SIZE && fgets(buffer, 255, fp))
  {
    sscanf(buffer, "%[^,]%*c%[^\n]", holdName, buffer);//read the country first, and keep the rest for the languages 
    .........
    
    /* Here is where I'm lost, I want to read a language, keep the rest of the buffer to repeat until
        the buffer is empty. But obviously I'm doing it wrong */
    while(sscanf(buffer, "%[^,]%*c%[^\n]", holdLang, buffer) != '\n')
    {
      ............
    }
    i++;
  }

Any help please?
I have this big program to do, and can't do anything else until I am able to read the whole file.

Thanks

Recommended Answers

All 2 Replies

This would be a good fit for strtok, if you're not locked into sscanf for any reason:

#include <stdio.h>
#include <string.h>

int main(void)
{
    FILE *in = fopen("test.txt", "r");
    char line[BUFSIZ];

    if (in != NULL) {
        while (fgets(line, sizeof line, in) != NULL) {
            char *tok = strtok(line, ",");

            if (tok == NULL)
                continue;

            printf("%s:\n", tok);

            while ((tok = strtok(NULL, ",")) != NULL)
                printf("\t%s\n", tok);
        }

        fclose(in);
    }

    return 0;
}

With sscanf you have to do a little more work because sscanf will always scan from the beginning of the string, it doesn't store the current position like a stream would. However, you can use the %n specifier to get the number of characters read and derive a position from that:

#include <stdio.h>

int main(void)
{
    FILE *in = fopen("test.txt", "r");
    char line[BUFSIZ];

    if (in != NULL) {
        while (fgets(line, sizeof line, in) != NULL) {
            char buf[BUFSIZ];
            int pos = 0;
            int n = 0;

            if (sscanf(line, "%[^,],%n", buf, &n) != 1)
                continue;

            printf("%s:\n", buf);
            pos += n;

            while (sscanf(line + pos, "%[^,\n]%*c%n", buf, &n) == 1) {
                printf("\t%s\n", buf);
                pos += n;
            }
        }

        fclose(in);
    }

    return 0;
}

Thank you very much!
I didn't know about strtok, or %n.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.