-1

i got a txt file write like this:

T,G,F,F
G,T,T,F
G,T,F,G
T,F,G,T

dimen = 4

and i want to import it into array,as dynamic allocating of chars like: [T,G,F,F,G,T,T,F,G,T,F,G,T,F,G,T]

i tried the code beyond but i got an error.

void file_2_arr(FILE *file,char *forest_current,int dimen)
{
    int i = 0;
    char *buffer = NULL;
    buffer =(char*)malloc(sizeof(char) * (2*dimen-1));
    const char* delim = ",";
    while (!feof(file))
    {
        fgets(buffer, sizeof buffer, file);
        char* token = strtok(buffer, delim);
        while (token != NULL)
        {
            printf("%s", token);
            strcpy(forest_current, token);
            token = strtok(NULL, delim);
            forest_current++;
        }
    }
    free(buffer);
    return;
Craig Estey
  • 30,627
  • 4
  • 24
  • 48
lasri23
  • 15
  • 3

1 Answers1

0

Your function is way too complicated. You're calling 5 functions and you really only need to call one.

You are doing:

fgets(buffer, sizeof buffer, file);

But, sizeof will return the size of the pointer and not the length of what you allocated. You want:

fgets(buffer, 2 * dimen - 1, file);

But, 2 * dimen - 1 is too short. It does not account for the newline at the end of the line [or the EOS char]. So, you need to change that to 2 * dimen + 2 both for fgets and malloc

Also, don't use feof. Just check the return value of fgets

You're using strtok to strip out a single character at a time. This is very slow.

Note that sizeof(char) is always 1 by definition. So, eliminate that.

It's not clear if you want an EOS character on the end of the output buffer or not. But, you're getting one.

Also, you did not show the code that calls your function, so how did you ensure that you had enough space in the caller's buffer?

You didn't actually specify what error you were actually getting, so it's a bit difficult to ensure that the above fixes your issues.

And, there is no need to cast the return of malloc. See: Do I cast the result of malloc?


If you read a char at a time, you don't need to use malloc or a separate buffer. Or, any other functions.

#include <stdio.h>

void
file_2_arr(FILE *file, char *forest_current, int dimen)
{

    while (1) {
        int chr = fgetc(file);
        if (chr == EOF)
            break;

        switch (chr) {
        case ',':
        case '\n':
            break;
        default:
            *forest_current++ = chr;
            break;
        }
    }

#if 0
    *forest_current = 0;
#endif
}
Craig Estey
  • 30,627
  • 4
  • 24
  • 48