c - C 中的 read() 错误

标签 c file io

我用 C 编写了一个学习文件 I/O 的玩具程序,以下是我的部分代码,这个程序的输出是错误的 - 我不知道我的代码有什么问题。

int fd = open(path_to_file, O_RDWR | O_APPEND | O_CREAT, 0777);
int size = 100;
int offset = 0;

write(fd, &size, sizeof(int));
write(fd, &offset, sizeof(int));
lseek(fd, 0, SEEK_SET);   /* start reading from the beginning */

int *size = malloc(sizeof(int));
int *offset = malloc(sizeof(int));

read(fd, size, sizeof(int));
read(fd, offset, sizeof(int));
printf("size is %d, offset is %d \n", *size, *offset);

free(size);
free(offset);

我得到的输出是:

大小为1953719668,偏移量为1684497779

这些数字很大,但它们应该分别是 100 和 0。我不明白这是怎么发生的。有人可以帮助理解这一点吗?

最佳答案

Ingo 说得对,如果文件已经存在,你可以追加到它...
为 1 个 int 分配内存不是很有效,但应该可以。
我猜你复制并粘贴了你的代码,变量上的相同名称阻止它编译。<​​br/>
即使文件存在,工作示例:

#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>

int main() {
  int fd = open("test.dat", O_RDWR | O_CREAT, 0777);
  int size = 100;
  int offset = 0;

  write(fd, &size, sizeof(int));
  write(fd, &offset, sizeof(int));
  lseek(fd, 0, SEEK_SET);   /* start reading from the beginning */

  int *result_size = malloc(sizeof(int));
  int *result_offset = malloc(sizeof(int));

  read(fd, result_size, sizeof(int));
  read(fd, result_offset, sizeof(int));
  printf("size is %d, offset is %d \n", *result_size, *result_offset);

  free(result_size);
  free(result_offset);
}

关于c - C 中的 read() 错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23248322/

相关文章:

c - 基本的 C 编程练习卡住了

Qt 通过 TCP 发送文件

c++ - 扩展精度浮点库 C/C++

java - 获取 FileNotFoundException

android - 检查 SD 卡上是否存在图像 - Android

Java BufferedReader IO 错误。流关闭

haskell - 更新后IORef仍然引用旧值

javascript - fs.readFileSync 始终返回空字符串

c - STM32L052 寄存器上的模数转换器

c++ - 适用于8位MCU的更快的16位乘法算法