[英]C - How to increment first int of a file
I have a file where i want the first sizeof(int)
bytes to store the number of elements following in the file.我有一个文件,我希望第一个
sizeof(int)
字节存储文件中后面的元素数。 I would like to increment this value whenever i add an element to the file.每当我向文件添加元素时,我都想增加这个值。
The code looks like this:代码如下所示:
int main() {
int val = 3;
FILE *file = fopen("hey", "wb");
fwrite(&val, sizeof(int), 1, file);
fclose(file);
increment_val();
}
void increment_val() {
int val;
FILE *file = fopen("hey", "ab+");
fread(&val, sizeof(int), 1, file);
val++;
fseek(file, 0, SEEK_SET);
fwrite(&val, sizeof(int), 1, file);
fseek(file, 0, SEEK_SET);
fread(&val, sizeof(int), 1, file);
printf("%d", val);
fclose(file);
}
I initialy write an int with the value 3 to the file.我最初将一个值为 3 的 int 写入文件。
I then read this value, increment it and write it back.然后我读取这个值,增加它并写回。
However when reading the value after this it still holds the original value of 3 instead of 4.但是,在此之后读取值时,它仍然保持原始值 3 而不是 4。
Interesting problem (thanks - good puzzle for the morning as I wasn't aware of this).有趣的问题(谢谢 - 早上的好谜题,因为我不知道这一点)。 But the underlying issue is that when you open for append, the writes ignore seeking.
但潜在的问题是,当您打开追加时,写入会忽略搜索。 Thus the code in
increment_val
should be:因此
increment_val
的代码应该是:
FILE *file = fopen("hey", "rb+");
Note that you don't need the b
really.请注意,您实际上不需要
b
。 You might be coming from python where that is signalling binary?你可能来自 python,那里是信号二进制?
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.