简体   繁体   English

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

[英]How Do I Store Contents of a File into an Array (C)

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.

Essentially, I want to be able to select any number in my array for later manipulation.本质上,我希望能够 select 数组中的任何数字以供以后操作。

Contents of address01:地址01的内容:

10 10

20 20

22 22

18 18

E10 E10

210 210

12 12

The prototype of fgets is fgets的原型是

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

You are using an int* ( int yup[8] ) where you should be using a char *.您正在使用 int* ( int yup[8] ),而您应该使用 char *。

If the address01 file you are reading is text, then you need to change your definition of yup.如果您正在阅读的 address01 文件是文本,那么您需要更改您对 yup 的定义。 If your file is binary you need to provide information on what the format of your binary is.如果您的文件是二进制文件,您需要提供有关二进制文件格式的信息。

The array you have defined is a pointer to an int array, but you need an array of char *.您定义的数组是一个指向 int 数组的指针,但您需要一个 char * 数组。 The other problem is that your yup variable is always pointing to the same address, so you are just overwriting the same memory.另一个问题是你的yup变量总是指向同一个地址,所以你只是覆盖了同一个 memory。 You need to allocation ( malloc() ) your yup variable before each fgets in order for each read to be placed in new memory.您需要在每个fgets之前分配( malloc() )您的 yup 变量,以便将每个读取放置在新的 memory 中。

Something like this:像这样的东西:

#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);
    }

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

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