[英]How do I get this file the first number of each line to increment it? And what about the first line not being skipped? In C
[英]C - How to increment first int of a file
我有一个文件,我希望第一个sizeof(int)
字节存储文件中后面的元素数。 每当我向文件添加元素时,我都想增加这个值。
代码如下所示:
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);
}
我最初将一个值为 3 的 int 写入文件。
然后我读取这个值,增加它并写回。
但是,在此之后读取值时,它仍然保持原始值 3 而不是 4。
有趣的问题(谢谢 - 早上的好谜题,因为我不知道这一点)。 但潜在的问题是,当您打开追加时,写入会忽略搜索。 因此increment_val
的代码应该是:
FILE *file = fopen("hey", "rb+");
请注意,您实际上不需要b
。 你可能来自 python,那里是信号二进制?
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.