作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
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
最佳答案
fgets的原型(prototype)是
char * fgets ( char * str, int num, FILE * stream );
您正在使用 int* (int yup[8]
),而您应该使用 char *。
如果您正在读取的address01文件是文本,那么您需要更改yup的定义。如果您的文件是二进制文件,您需要提供有关二进制格式的信息。
你定义的数组是一个指向int数组的指针,但是你需要一个char *的数组。另一个问题是您的 yup 变量始终指向相同的地址,因此您只是覆盖相同的内存。您需要在每个 fgets
之前分配 (malloc()
) 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);
}
关于c - 如何将文件的内容存储到数组中(C),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58869283/
我是一名优秀的程序员,十分优秀!