【问题标题】:Reading Multiple lines(different lengths) from file in c从c中的文件中读取多行(不同长度)
【发布时间】:2015-07-09 05:39:56
【问题描述】:

我想将文件的以下内容加载到数组中。 文件内容:

[1,2,3,4,5]
[2,3]
[2]
[1,4,5,6,8,9]

现在,我想将第一行加载到整数数组'a' ( a ={1,2,3,4,5}) 中并进行一些操作。免费 a.取下一行并加载到'a' (a = {2,3}) 并执行一些操作等等......直到文件结束。

注意:每行可以有不同的数字计数。(我们不知道每行的数字计数)

如何扫描每一行并只取数字并将它们存储在数组中?
我的代码:

#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <string.h>
#include <unistd.h>
#include <sys/types.h> 
#include <sys/stat.h>
#include <fcntl.h>

#define DELIM " \r\n\t!@#$%^&*()_+-={}|\\:\"'?¿/.,<>’¡º×÷‘"

int main(int argc, char *argv[]){
    int lineIdx = 0;
    int charIdx = 0;
    int TERMINATOR = 1753775;
    char *token = "tmp";
    char *orLine = malloc(4096 * sizeof(char));
    char **importedLine = malloc(4096 * sizeof(orLine));
    int tokenizedArray[100][100];// = malloc(sizeof(orLine * numOfLines));

    FILE *f = fopen(argv[1], "r");

    while(fscanf(f, "%s", orLine) != EOF){
        importedLine[lineIdx] = orLine;
        for(charIdx = 0; charIdx < strlen(importedLine[lineIdx]); charIdx++){
            importedLine[lineIdx][charIdx] = importedLine[(lineIdx)][(charIdx+1)];
        }
        importedLine[lineIdx][(strlen(importedLine[lineIdx])-1)] = NULL;
        token = strtok(importedLine[lineIdx], ", ");
        charIdx = 0;
        while(token != NULL){
            tokenizedArray[lineIdx][charIdx] = atoi(token);
            token = strtok(NULL, ", ");
            charIdx++;
        }
        tokenizedArray[lineIdx][(charIdx)] = TERMINATOR;
        lineIdx++;
    }
    tokenizedArray[(lineIdx)][0] = TERMINATOR;
    fclose(f);
    lineIdx = 0;
    charIdx = 0;
    while(tokenizedArray[lineIdx][charIdx] != TERMINATOR){
        while(tokenizedArray[lineIdx][charIdx] != TERMINATOR){
            printf("%d ",tokenizedArray[lineIdx][charIdx]);
            charIdx++;
        }
        lineIdx++;
        charIdx = 0;
        printf("\n");
    }
    return 0;
}

提前致谢

【问题讨论】:

  • 代码最终将成为解决此问题的必要条件。展示你的,也许我们可以告诉你你做错了什么以及如何纠正它。
  • @LakshmanKollipara 请添加您的代码,以便我们帮助您改进它。
  • 欢迎来到 Stack Overflow!请拨打tour 并阅读How to Ask 以了解我们对这里问题的期望。请注意,我们不提供 from-scratch 编码服务。请告诉我们您已经尝试过什么,它是如何失败的,我们也许可以提供帮助。:-)
  • 这是我的代码的链接。 [链接] (dpaste.com/3XKB80E) 和输入文件。 [链接] (dpaste.com/0V2J3MA)。

标签: c arrays file file-io


【解决方案1】:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

typedef int Type;

typedef struct vector {
    size_t size;
    size_t capacity;
    Type *array;
} Vector;

Vector *vec_make(void){
    Vector *v = malloc(sizeof(*v));
    if(v){
        v->size = 0;
        v->capacity=16;
        v->array = malloc(v->capacity * sizeof(Type));
    }
    return v;
}

void vec_free(Vector *v){
    free(v->array);
    free(v);
}

void vec_add(Vector *v, Type value){
    v->array[v->size++] = value;
    if(v->size == v->capacity){
        Type *temp;
        temp = realloc(v->array, sizeof(Type)*(v->capacity += 16));
        if(!temp){
            perror("realloc at vec_add");
            vec_free(v);
            exit(-1);
        }
        v->array = temp;
    }
}

int main(int argc, char *argv[]){
    if(argc != 2){
        fprintf(stderr, "Usage : %s filename\n", argv[0]);
        exit(EXIT_FAILURE);
    }

    FILE *f = fopen(argv[1], "r");
    if(f == NULL){
        perror("fopen");
        exit(EXIT_FAILURE);
    }

    char line[4096];
    while(fgets(line, sizeof line, f)){
        static const char *delimiter = "[,] \t\n";
        Vector *v = vec_make();

        char *number = strtok(line, delimiter);//Format don't check
        for(; number; number = strtok(NULL, delimiter)){
            vec_add(v, atoi(number));
        }
        //some operation : print out
        int size = v->size;
        int *a = v->array;
        for(int i = 0; i < size; ++i){
            if(i)
                putchar(',');
            printf("%d", a[i]);
        }
        putchar('\n');
        vec_free(v);
    }
    fclose(f);
    return 0;
}

【讨论】:

    【解决方案2】:

    按照以下步骤操作:

    1. 阅读完整的一行
    2. 检查您的语法是否正确:行必须以[ 开头并以] 结尾
    3. 删除这些方括号
    4. , 处拆分行。现在你知道元素的数量了
    5. 分配这个长度的数组
    6. 将所有子字段解析为整数

    【讨论】:

    • 谢谢@DrKoch。你能详细说明一下吗。我是一名非 CS 人员,最近开始研究 C 和文件。
    • 好吧,先自己试试,展现你的努力。届时,每个人都会很乐意为您提供帮助。
    【解决方案3】:

    大概

    1 第一次以阅读模式打开文件FILE*p;p=fopen("file.txt","r");

    2 取任意字符数组说

    char acline[40];int i;

    3 现在使用循环逐行读取文件内容并将它们存储到acline

    while (!feof(p)) {for(i=0;i&lt;40;i++)acline[i]=NULL;fgets(acline,40,p);// your code , whole line is in your array , insert if condition to check []}

    4 关闭文件fclose(p);

    使用 while(!feof(p)) 有一些问题!

    【讨论】:

    • 他应该知道feof() 内的while 循环会产生问题。而是可以使用fgets()
    • 是的,我在最后一行提到过。
    【解决方案4】:

    A.使用一个int temporary_array[BIG_ENOUGH];

    B.使用两个整数变量,int num;int i=0;,一个整数指针,int *a

    C.打开文件

    D.阅读每个字符。对每个字符执行以下操作:

    1. 如果字符的 ascii 代码是数字,则执行 num = whatEverThatNumberIs;。然后做temporary_array [i] =num;i++;

    2. 当您收到\n 时,您就有了一条线路。执行a = malloc(i*sizeof (int)); 然后将每个元素从temporary_array [ ] 复制到a [ ]。然后i=0;

      现在你有你的阵列a [i]。在这个数组中做你想做的操作。

    3. free (a);

    执行此操作,直到到达文件末尾。我想这是你可以做到的一种方式。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2023-04-05
      • 2018-06-04
      • 1970-01-01
      • 2014-12-19
      • 1970-01-01
      • 1970-01-01
      • 2015-08-01
      相关资源
      最近更新 更多