C - 从文本文件中读取多行

时间:2011-08-11 10:18:07

标签: c file text

这很可能是一个愚蠢的问题! 我有一个填充随机数的文本文件,我想将这些数字读成数组。

我的文本文件如下所示:

1231231 123213 123123
1231231 123213 123123
0

1231231 123213 123123
1231231 123213 123123
0

依此类推。这段数字以0

结尾

这是我到目前为止所尝试的:

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

if(file != NULL)
{
    while(fgets(line, sizeof line, file) != NULL)
    {
        fputs(line, stdout);
    }
    fclose(file);
}

这显然不起作用,因为我将每一行读入同一个变量。

如何阅读这些行,当该行获得以0结尾的行时,将该段文本存储到数组中?

感谢所有帮助。

1 个答案:

答案 0 :(得分:1)

您只需将从文件中读取的数字存储在某个永久存储中!此外,您可能希望解析各个数字并获取其数字表示。那么,有三个步骤:

  1. 分配一些内存来保存数字。数组数组看起来像一个有用的概念,每个数字块都有一个数组。

  2. 使用strtok将每一行标记为对应于一个数字的字符串。

  3. 使用atoistrtol将每个数字解析为整数。

  4. 以下是一些示例代码,可帮助您入门:

    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);
            }
        }
    }
    

    最后,你需要释放内存:

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