我如何将文件内容存储到数组(C)中

问题描述 投票:0回答:1
FILE *pFile;
pFile = fopen("address01", "r");
int  yup[8];
int*  array[7];

for (int i = 0;i < 7; i++) {
    while (!feof(pFile)) {
        fgets(yup, 8, pFile);
        puts(yup);     //It DOES print each line
        array[i] = yup;
    }
}
fclose(pFile);
printf("First: %d",array[0]);     //I want it to print the first thing in the file, but I get a
                                  //crazy number. It should be 10.
printf("Second: %d",array[1]);    //I want it to print the 2nd thing in the file, but I get a
                                  //crazy number. It should be 20
                                  //etc.

基本上,我希望能够在数组中选择任何数字以供以后使用。

地址01的内容:

10

20

22

18

E10

210

12

c arrays scanf fgets
1个回答
0
投票

fgets的原型是

char * fgets ( char * str, int num, FILE * stream );

您正在使用int *(int yup[8]),而您应该在其中使用char *。

如果您正在读取的address01文件是文本,那么您需要更改yup的定义。如果文件是二进制文件,则需要提供有关二进制文件格式的信息。

您定义的数组是一个指向int数组的指针,但是您需要一个char *数组。另一个问题是您的yup变量始终指向相同的地址,因此您只是覆盖了相同的内存。您需要在每个malloc()之前分配(fgets)您的yup变量,以便将每次读取都放入新的内存中。

类似这样的东西:

#include <stdio.h>
#include <stdlib.h>

int main(void) {
    FILE *pFile;
    pFile = fopen("address01", "r");
    char *yup;
    char *array[7];

    for (int i = 0;i < 7; i++) {
        yup = (char *) malloc(8);
        if (yup == NULL) {
            // this indicates you are out of memory and you need to do something
            // like exit the program, or free memory
            printf("out of memory\n");
            return 4; // assuming this is running from main(), so this just exits with a return code of 4
            }
        if (feof(pFile)) {
            break; // we are at the end, nothing left to read
            }
        fgets(yup, 8, pFile);
        puts(yup); 
        array[i] = yup;
        }
    fclose(pFile);
    }
© www.soinside.com 2019 - 2024. All rights reserved.