user1828595
user1828595

Reputation:

Parsing Comma Separated File in C

I'm trying to parse a file in C that is a comprised of sets of numbers (one per line). Each set is separated by a comma. For some reason I'm getting an incorrect output.

Example input: 1,2,4,8,55,777 Output: A bunch of what seem to be memory addresses. And when I print off the strings it's not reading 55 or 777 (or any number over two digits).

int * parseFile(char *input, int *set, int line)
{
    char buf[BUF_SIZE];
    char *token = (char *) malloc(10 * sizeof(char));
    int i;

    FILE *f = fopen(input, "r");

    for (i = 1; i < line; i++)
        fgets(buf, BUF_SIZE, f);

    memset(buf, 0, BUF_SIZE); // Clear the buffer.
    i = 0;

    if (fgets(buf, BUF_SIZE, f) != NULL) {
        token = strtok(buf, ",");
        set[i] = atoi(token);
        i++;

       while (set[i] != 0) {
            printf("%d\n", set[i]);
            set[i] = atoi(token);
            i++;

            token = strtok(NULL, ",");
        }
    }

    fclose(f);

    return set;
}

Upvotes: 0

Views: 1926

Answers (4)

9mjb
9mjb

Reputation: 583

I like this

 if (fgets(buf, BUF_SIZE, f) != NULL) {
    token = strtok(buf, ",");
    for (i=0; token != NULL; i++) {
      set[i] = atoi(token);
      // Optional: if (set[i] == 0) break; // I don't know why to stop on 0
      printf("%d\n", set[i]);
      token = strtok(NULL, ",");
    }
  }

The break is a little ugly, but it's better than

for (i=0; (token != NULL) && ((set[i] = atoi(token)) != 0); i++) {

Upvotes: 0

MOHAMED
MOHAMED

Reputation: 43548

you can use fscanf()

use the following fscanf() into a loop till you reach the end of the file:

int a,b,c,d,e,x;
while (fscanf(f, " %d , %d , %d , %d, %d , %d", &a, &b, &c, &d, &e, &x) != EOF) {....}

Upvotes: 1

user2038893
user2038893

Reputation: 344

You are printing the value of set[i] before you assign to it the value of atoi. Consider:

set[i] = atoi(token);
printf("%d,",set[i]); 

while (set[i] != 0) {
    i++;
    set[i] = atoi(token);
    printf("%d,",set[i]); 
}

Upvotes: 0

Peter Miehle
Peter Miehle

Reputation: 6070

I am very confused with this:

set[i] = atoi(token); //i = 0
i++; //i = 1

while (set[i] != 0) { //set[1] = ???
  printf(...set[i]); 
  set[i] = atoi(token);
  i++;
  ...

so, depending on the previous content of the array "set", you decide, whether to read the next value. So, if you did a "memset(set, 0, sizeof(set));" you actually read one line. If you did not clear the "set", if may contain rubbish, which you "printf()" before readin the next value

Upvotes: 0

Related Questions