int check[sizeof(char)*4]; //creates a buffer array 4 bytes long
这是不正确的。您正在创建一个由四个整数组成的数组,每个整数通常为 32 位,然后当您 printf("%d",check) 打印该数组的地址时,该地址可能会在您每次运行程序时发生变化。我想你想要的是这样的:
if (fp = fopen("filesysFile-full", "r")) {
fseek(fp, 1044, SEEK_SET); //Goes to 1024th byte
int check; //creates a buffer array the size of one integer
fread(&check, 1, sizeof(int), fp); //reads an integer (presumably 1) from the file
printf("%d",check); //prints
int close = fclose(fp);
if (close == 0) {
printf("Closed");
}
}
请注意,不是声明一个整数数组,而是只声明一个。还要注意从 fread(check, ...) 到 fread(&check, ...) 的变化。fread的第一个参数是要读取数据的缓冲区的地址(在本例中为单个整数)。
请记住,虽然整数可能是 32 位长,但这并不能保证。此外,在大多数操作系统中,整数以最低有效字节首先存储在磁盘上,因此如果磁盘上的数据在字节 1044 处看起来像这样,您只会读取 1:
0x01 0x00 0x00 0x00
如果相反,0x00 00 00 01,将被读取为 16777216 (0x01000000)。
如果要读取多个整数,可以使用数组,如下所示:
if (fp = fopen("filesysFile-full", "r")) {
fseek(fp, 1044, SEEK_SET); //Goes to 1024th byte
int check[10]; //creates a buffer of ten integers
fread(check, 10, sizeof(int), fp); //reads 10 integers into the array
for (int i = 0; i < 10; i++)
printf("%d ", check[i]); //prints
int close = fclose(fp);
if (close == 0) {
printf("Closed");
}
}
在这种情况下,check(不带括号)是指向数组的指针,这就是我将 fread 改回 fread(check, ...) 的原因。
希望这可以帮助!