【问题标题】:Reading a changeable lines file from command line and store从命令行读取可变行文件并存储
【发布时间】:2018-08-12 02:34:13
【问题描述】:

我要从命令行读取一个文件。我想将行存储在数组中。但问题是我不知道行数。所以我不知道如何将它动态存储在数组中。所以请帮忙。 (通过给出一些示例代码)

【问题讨论】:

标签: c arrays file multidimensional-array dynamic


【解决方案1】:
#define _GNU_SOURCE
#include <stdio.h>
#include <stdlib.h>
#include<string.h>
int main(void)
{
    FILE * fp;
    char * line = NULL;
    size_t len = 0;
    ssize_t read;
    int i=0;
    char **A;
    A = (char **)malloc(sizeof(char *)*1); //creating char array of a[0][]

    fp = fopen("/etc/motd", "r");
    if (fp == NULL)
        exit(EXIT_FAILURE);

    while ((read = getline(&line, &len, fp)) != -1) {
        A = (char **)realloc(A, sizeof(char **)*(i+1)); // adding one more row to array
        *(A+i) = (char *)malloc(sizeof(char)*read); //adding required column
        strcpy(A[i],line); // copying line to i-th raw of array
        i++;
    }

    fclose(fp);
    if (line)
        free(line);
    exit(EXIT_SUCCESS);
}

【讨论】:

    【解决方案2】:

    使用两个循环,在第一个循环中检查每一行的大小并添加到一个变量中。一旦到达文件末尾,您将获得将文件存储在数组中所需的总字节数。现在使用该总字节变量将内存动态分配给数组。现在开始第二个循环,读取每一行并存储到该数组中。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-05-09
      • 2016-06-19
      • 2017-11-05
      • 1970-01-01
      相关资源
      最近更新 更多