codej
codej

Reputation: 1

Arrays not incrementing properly when reading from a file in C

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

#define ARRAY_MAX 100

int main() {

    FILE *input, *output;
    char *token[100];
    char buf[100];
    int count = 0;
    input = fopen("/Users/home/Desktop/test.txt", "r");
    output = fopen("/Users/home/Desktop/test2.txt", "w");

    while (fgets(buf, sizeof(buf), input) != NULL) {
        token[count] = strtok(buf, "\n");
        ++count;
    }

    for (int i = 0; i<count; i++) {
        printf("%s\n", token[i]);
    }

    printf("%d\n\n" ,count);
    return 0 ;

}

When I run this code I get the output like

line 3

line 3

line 3

rather than getting a result like

line 1

line 2

line 3

What an I doing wrong?

Upvotes: 0

Views: 47

Answers (2)

Lee Daniel Crocker
Lee Daniel Crocker

Reputation: 13196

The assignment

token[count] = ...

merely copies the address of the buffer into the pointer. You then re-use the same buffer, and copy the same address into the next element of the array. What you need to do is allocate memory for each new line as it is read and copy the contents of the buffer into the newly allocated memory:

token[count] = malloc(strlen(buf) + 1); // +1 for trailing 0
strcpy(token[count], buf);

Upvotes: 1

Paul Roub
Paul Roub

Reputation: 36448

strtok() is being run on the same buf each time, and so will return the same address each time. When the loop completes, the last-read value is in the buffer, so that's what prints.

You want to save copies of the lines:

while (fgets(buf, sizeof(buf), input) != NULL) {
    token[count] = strdup( strtok(buf, "\n") );
    ++count;
}

Upvotes: 2

Related Questions