c - 读取文件并在每行的开头添加 10 个数组元素读取到数组我正在存储文件的行

标签 c arrays file-io

我正在读取一个文件,并将文件中的字符单独存储到数组中。 我的问题是:在读取文件时,如何在读取新行之前向数组插入 10 个元素。

示例:

File:

471 22 01 05 34 75 78 65 46 34 20 19

521 01 02 03 45 35 42 36 87 99 12 23 12 37 64

当我读取文件时,它应该像这样结束:

[V0,V1,V2,V3,V4,V5,V6,V7,V8,V9,22,01,05,34,75,78,65,46,34,20,19,V0,V1,V2,V3,V4,V5,V6,V7,V8,V9,01,02,03,45,35,42,36,87,99,12,23,12,37,64]

我目前的想法是:

在开始读取文件之前,我已经将前 10 个元素插入到数组中。然后在读取文件时,每当我找到“\0”时,我都会使用循环再次插入变量,这就是我得到的:

        Elements = [V0,V1,V2,V3,V4,V5,V6,V7,V8,V9];//array of elements to insert

        int i = 0;
        int j = 0;

        //this loop reads the file and ignores what's not necessary(it's working properly)

        while(s2[i] != '\0')//reading chars from the file
        {
            if(s2[i] == ' ')
                i++;

            MEM[j]=atoi((s2+i));//MEM is the array in which i'm storing the lines

            i += 3;//increment by 3 due to problem specifics(needs to ignore the first 3 values from the file)
            j++;
        }

我知道我的想法不是很有效,但我是 C 新手,我不知道如何正确地做到这一点。

有谁知道更好的方法吗? 谢谢

最佳答案

如您所示,输入文件包含

471 22 01 05 34 75 78 65 46 34 20 19
521 01 02 03 45 35 42 36 87 99 12 23 12 37 64

您可以使用 fscanf() 逐字读取,而不是逐个字符读取,因为显示的文件由相似的类型组成(全部是数字)。来自 fscanf() 的手册页。

int fscanf(FILE *stream, const char *format, ...); 

每次调用realloc()读取一一整数并分配动态内存,在这种情况下您无需担心数组的大小。以下是从文件读取数据并将数据存储到整数数组中的示例代码。

int main(void) {
        FILE *fp = fopen("input.txt","r");
        if(fp == NULL){
                /*.. error handling */
                return 0;
        }
        int row = 1;
        int *input = malloc(sizeof(*input));/*1st time 4 byte, to store first integer inside file */
        /*  here input is dynamic array */
        while(fscanf(fp,"%d",&input[row-1]) == 1) { /* fscanf() read upto whitespace at a time */
                row++;
                input = realloc(input,row * sizeof(*input));/* reallocate based on number of input */
        }
        for(int index = 0 ; index < row-1 ;index++) {
                printf("%d\n",input[index]);
        }
        /* free dynamically allocated memory @TODO*/
        return 0;
}

关于c - 读取文件并在每行的开头添加 10 个数组元素读取到数组我正在存储文件的行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50305686/

相关文章:

c++ - png block 的 CRC32 计算与真实 block 不匹配

C 程序条件无法识别可操作的输入

java - 如何从 Java 中的二维数组中删除占位值?

python - 为什么我的正则表达式对来自 file.read() 的输入不起作用?

file-io - 编写 netcdf4 文件比编写 netcdf3_classic 文件慢 6 倍,而文件大 8 倍?

c - 段错误 : don't know where to start

c - 在 C 中,当输入是字符串/字符时,我可以使用枚举打印枚举的编号吗?

javascript - JS : find and merge similar objects in array by key

c - 如何在C函数中访问这个结构体数组?

python - 如何打开一个文件进行读写?