简体   繁体   English

如何从输入文件在C中创建字符串的动态数组

[英]how to create a dynamic array of strings in C from an input file

Haven't done any C programming in awhile but I have the following that outputs a string but I'd like to put it into an array that I can then manipulate (at the --------- in comments in the code). 一段时间未进行任何C编程,但是我有以下输出字符串的内容,但我想将其放入一个数组中,然后可以操作(在---------中的注释中)码)。 I would think I need to declare the size of the array but need to handle a variable amount. 我想我需要声明数组的大小,但需要处理可变数量。 Was thinking of doing something like system('wc -l filename') but that sounds really awful. 正在考虑做类似system('wc -l filename')事情,但这听起来确实很糟糕。 Must be a better way: 必须是更好的方法:

#include <stdio.h>

int main()
{
    char *inname = "test.txt";
    FILE *infile;
    char line_buffer[BUFSIZ]; /* BUFSIZ is defined if you include stdio.h */
    char line_number;

    infile = fopen(inname, "r");
    if (!infile) {
        printf("Couldn't open file %s for reading.\n", inname);
        return 0;
    }
    printf("Opened file %s for reading.\n", inname);

    line_number = 0;
    while (fgets(line_buffer, sizeof(line_buffer), infile)) {
        ++line_number;
        /* note that the newline is in the buffer */
        // ---------------------
        // would like to put into an array of strings here rather than just printf'ing out out

         printf("%4d: %s", line_number, line_buffer);
    }
    printf("\nTotal number of lines = %d\n", line_number);
    return 0;
}

First of all: 首先:

char *inname = "test.txt";

should be 应该

const char *inname = "test.txt";

Then, you want to allocate an array big enough to store all the lines. 然后,您要分配一个足以存储所有行的数组。 Since you don't know the number of lines beforehand, you can use exponential storage expansion: double the size of the array when it's exhausted. 由于您事先不知道行数,因此可以使用指数存储扩展:用尽数组时将其大小加倍。

Sample code (error checking omitted for clarity, don't copy-paste this into production code): 示例代码(为清楚起见,省略了错误检查,请勿将其复制粘贴到生产代码中):

size_t n = 0;
size_t alloc_size = 4;
char buffer[LINE_MAX];

char **arr = malloc(alloc_size * sizeof arr[0]);

while (fgets(buffer, sizeof buffer, fp) != NULL) {
    if (++n > alloc_size) {
        alloc_size *= 2;
        arr = realloc(arr, alloc_size * sizeof arr[0]); // don't do this
    }

    arr[n - 1] = strdup(buffer);
}

Unfortunately there is no dynamic array in C (if you are thinking of something like vector in C++). 不幸的是,C中没有动态数组(如果您考虑的是C ++中的vector)。 You could use list and each time you are reading line from file just append new list entry at the end of list. 您可以使用列表,每次从文件中读取行时,只需在列表末尾添加新的列表条目即可。

There is also "dynamic" array since C99 called VLA (variable length array). 自从C99被称为VLA(可变长度数组)以来,还存在“动态”数组。 You can declare array with dynamic size (or rather known while program is running), but this will not help you with your problem as you will have to every time declare new array with size bigger than previous one and copy content of old to new - this would be very inefficient. 您可以声明具有动态大小的数组(或者在程序运行时知道),但这将无济于事,因为您每次必须声明大小大于先前数组的新数组并将旧内容复制到新内容时-这将是非常低效的。

So summing up there could be hard to find something better than list. 因此,总结起来可能很难找到比列表更好的东西。

You could go through the whole file (slow if the file is big) and count every "new line". 您可以浏览整个文件(如果文件很大,则比较慢)并计算每条“新行”。 Then create an array with this count size and then rewind the file and read in every line. 然后创建一个具有此计数大小的数组,然后倒回文件并读取每一行。

mfg MFG

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM