c - 从c中的fread()形式读取缓冲区数据

标签 c arrays buffer cs50

我正在尝试从文件中提取数据并将其直接存储在 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/

相关文章:

delphi - 如何刷新 TFileStream?

c - 如何阻止 Cygwin 下的 gcc 将 ".exe"添加到已编译的可执行文件中?

node.js - 如何检测 Node.js 缓冲区中的编码错误

c - 如何在 sprintf() 中获取追加模式

javascript - 使用 jQuery 在 javascript 中迭代关联数组(键/值对),其中值是 jQuery 对象

javascript - findIndex() javascript 数组对象

javascript - 如何访问和处理嵌套对象,数组或JSON?

java - 如何检查队列中的鼠标事件

c - 有多少空字节,在 C 中连接字符串

c - 在 C 中对二维结构数组进行排序时出现问题