[英]Why does fseek work when you are writing (fwrite) to a binary file, but when reading (fread) it doesn't? - C
basically my problem is that when I use the following program: 基本上我的问题是,当我使用以下程序时:
#include <stdlib.h>
#include <stdio.h>
#define SIZE 1000
int main() {
FILE *fp;
int r, i;
char fp_string[600] = "/Users/mac/Library/Mobile Documents/com~apple~CloudDocs/College/Program With Persistent Data/Lab 3/num1000.bin";
fp = fopen(fp_string, "rb+");
r = 11;
fseek(fp, 3 * sizeof(int), SEEK_SET);
fwrite(&r, sizeof(int), 1, fp);
fseek(fp, 10 * sizeof(int), SEEK_SET);
fwrite(&r, sizeof(int), 1, fp);
fclose(fp);
return 0;
}
It updates the binary file (which is 1000 integers) with the 3rd and 10th digits to be 11. 它更新二进制文件(1000个整数),第3个和第10个数字为11。
But when I do the following: 但是当我做以下事情时:
#include <stdlib.h>
#include <stdio.h>
#define SIZE 1000
int main() {
FILE *fp;
int r, i;
char fp_string[600] = "/Users/mac/Library/Mobile Documents/com~apple~CloudDocs/College/Program With Persistent Data/Lab 3/num1000.bin";
fp = fopen(fp_string, "rb+");
r = 11;
printf("\n\n Before making any changes:\n");
for (i = 0; i < SIZE; i++) {
fseek(fp, i * sizeof(int), SEEK_SET);
fread(&r, sizeof(int), 1, fp);
printf("%d ", r);
}
fseek(fp, 3 * sizeof(int), SEEK_SET);
fwrite(&r, sizeof(int), 1, fp);
fseek(fp, 10 * sizeof(int), SEEK_SET);
fwrite(&r, sizeof(int), 1, fp);
printf("\n\n After making changes:\n");
fseek(fp, 0, SEEK_SET);
for (i = 0; i < SIZE; i++) {
fread(&r, sizeof(int), 1, fp);
printf("%d ", r);
}
fclose(fp);
return 0;
}
It doesn't change anything at all. 它根本不会改变任何东西。 Just in case you where wondering, to check if the first program worked what I did is:
万一你想知道,检查第一个程序是否有效我做的是:
That way it worked, but the first program doesn't seem to change anything, it shows the exact same numbers again. 这样它起作用,但第一个程序似乎没有改变任何东西,它再次显示完全相同的数字。
#include <stdlib.h>
#include <stdio.h>
#define SIZE 1000
int main() {
FILE *fp;
int r, i;
char fp_string[600] = "/Users/mac/Library/Mobile Documents/com~apple~CloudDocs/College/Program With Persistent Data/Lab 3/num1000.bin";
fp = fopen(fp_string, "rb");
for (i=0;i<SIZE;i++) {
fread(&r, sizeof(int), 1, fp);
printf("%d ", r);
}
fclose(fp);
return 0;
}
The first for
loop is reading every number in the file into r
before printing them. 第一个
for
循环是在打印之前将文件中的每个数字读入r
。 At the end of the loop, r
contains the last number in the file, and that gets written into the places where you seek. 在循环结束时,
r
包含文件中的最后一个数字,并将其写入您寻找的位置。
Either use a different variable in the loop, or put the r = 11;
在循环中使用不同的变量,或者将
r = 11;
assignment after the loop. 循环后的赋值。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.