开发者

C - Reading multiline from text file

This is most likely a dumb question! I have a text file filled with random numbers and I would like to read these numbers into an array.

My text file looks like this:

1231231 123213 123123
1231231 123213 123123
0

1231231 123213 123123
1231231 123213 123123
0

And so on.. The piece of numberse ends with 0

This is what I have tried so far:

FILE *file = fopen("c:\\Text.txt", "rt");
char line[512];

if(file != NULL)
{
    while(fgets(line, sizeof line, file) != NULL)
    {
        fputs(line, s开发者_StackOverflow中文版tdout);
    }
    fclose(file);
}

This does clearly not work, since I read each line into the same variable.

How can I read the lines and when the line gets the line where it ends with 0, then store that piece of text into an array?

All help is appreciated.


You just have to store the numbers that you read from the file in some permanent storage! Also, you probably want to parse the individual numbers and obtain their numerical representation. So, three steps:

  1. Allocate some memory to hold the numbers. An array of arrays looks like a useful concept, one array for each block of numbers.

  2. Tokenize each line into strings corresponding to one number each, using strtok.

  3. Parse each number into an integer using atoi or strtol.

Here's some example code to get you started:

FILE *file = fopen("c:\\Text.txt", "rt");
char line[512];

int ** storage;
unsigned int storage_size = 10; // let's start with something simple
unsigned int storage_current = 0;

storage = malloc(sizeof(int*) * storage_size); // later we realloc() if needed

if (file != NULL)
{
    unsigned int block_size = 10;
    unsigned int block_current = 0;

    storage[storage_current] = malloc(sizeof(int) * block_size); // realloc() when needed

    while(fgets(line, sizeof line, file) != NULL)
    {
        char * tch = strtok (line, " ");
        while (tch != NULL)
        {
            /* token is at tch, do whatever you want with it! */

            storage[storage_current][block_current] = strtol(tch, NULL);

            tch = strtok(NULL, " ");

            if (storage[storage_current][block_current] == 0)
            {
                ++storage_current;
                break;
            }

            ++block_current;

            /* Grow the array "storage[storage_current]" if necessary */
            if (block_current >= block_size)
            {
                block_size *= 2;
                storage[storage_current] = realloc(storage[storage_current], sizeof(int) * block_size);
            }
        }

        /* Grow the array "storage" if necessary */
        if (storage_current >= storage_size)
        {
            storage_size *= 2;
            storage = realloc(storage, sizeof(int*) * storage_size);
        }
    }
}

In the end, you need to free the memory:

for (unsigned int i = 0; i <= storage_current; ++i)
    free(storage[i]);
free(storage);
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜