我正在尝试从文件中提取数据并将其直接存储在 fread 函数的数组中。不过好像数据类型不对?
这是错误消息:
dataPlus.c:28:15: error: incompatible integer to pointer conversion passing 'int' to parameter of type 'void *' [-Werror,-Wint-conversion] fread(ptr[i], 1, 1, in);
如何才能访问这些数据?例如,如果我想检查文本文件中的前 3 个字符是否为 1、2 和 3。
/**
* To store specific lines of data from fread into array.
* Alternatively, to make the buffer recieved from fread, readible
**/
#include <stdio.h>
int main(void)
{
FILE* in = fopen("in.txt", "r");
if (in == NULL)
{
printf("File does not exist.\n");
return 1;
}
FILE* out = fopen("out.txt", "w");
//read file information into array.
int ptr[4];
//error here... Tried to store it directly into array instead of buffer..
for(int i = 0; i < 4; i++)
{
fread(ptr[i], 1, 1, in);
}
for(int j = 0; j < 4; j++)
{
printf("success. Array[%i] is --> %i value\n", j, ptr[j]);
}
fclose(in);
fclose(out);
}
最佳答案
在 C 中,指针和数组完全相同,因此 int ptr[4];
意味着您有一个包含 4 个整数的数组,您可以使用通常的表示法来访问它们(例如 ptr[3] = 2;
) 或者,使用指针算术,*(ptr+3) = 2;
,其作用相同。
函数fread()
需要某种类型的指针,因此您必须给它一个地址,在您的情况下是(运算符&
)i的地址: 数组中的第一个元素,如 fread(&(ptr[i]), 1, 1, in);
或 fread(ptr + i, 1, 1, in);
编译器错误说明了这一点,您向函数提供了一个整数而不是指针。
关于c - 从c中的fread()形式读取缓冲区数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40895773/