c - Write data after fseek(), ftell() output is wrong, the data written before fseek() are all 0
问题描述
I first write 88, then use fseek()
to position the file pointer to the beginning, and write 99, then position the file pointer to the end, use ftell()
to view the size of the file (the target is sizeof(int) + sizeof(int) = 8), but got 4.
Finally, I tried to print out the two values I wrote (the target is 98, 88), but 99, 0 was output.
#include <stdio.h>
int main() {
FILE* fp = fopen("a", "wb");
int a = 88;
fwrite(&a, sizeof(int), 1, fp);
fseek(fp, 0, SEEK_SET);
int c = 98;
fwrite(&c, sizeof(int), 1, fp);
fseek(fp, 0, SEEK_END);
printf("%d\n", ftell(fp));
FILE* fpc = fopen("a", "rb");
int b;
fread(&b, sizeof(int), 1, fpc);
int d;
fread(&d, sizeof(int), 1, fpc);
printf("%d, %d\n", b, d); // 98, 0
}
gcc version 9.3.0 (Ubuntu 9.3.0-17ubuntu1~20.04)
解决方案
推荐阅读
- bash - Bash:在 X 列中保留所有具有重复值的行
- batch-file - 批量重命名子文件夹中的文件名
- docker - 这就是我在从詹金斯调用的shell脚本中构建图像和部署的方式?
- python - Openpyxl - 从 Excel 文件中的所有工作表中删除格式
- javascript - 在数组 AJAX/NodeJS 中推送数据
- python - Running parallel python scripts from bash file
- ruby-on-rails - MacOS Catalina 上的多个 Ruby 和 gem。如何卸载以及在 Mac 上安装干净的 ruby/gem/bundler 的最佳选择
- reactjs - React typescript - 类型'boolean'不可分配给类型
- javascript - Selenium 点击导致页面弹出错误登陆页面
- python - 调用函数后的 (x) 是什么意思?