Question

I wrote a toy program to learn file I/O in C, the following is part of my code, and the output from this program is just wrong - I've no idea what is wrong in my code.

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);

The output I got is:

size is 1953719668, offset is 1684497779

These numbers are so huge, but they should be 100, and 0, respectively. I don't understand how this happens. Could someone offer help with understanding this?

Was it helpful?

Solution

Ingo has it right, if the file already exists you append to it...
Mallocing for 1 single int is not very efficient, but that should work.
I guess you copied and pasted your code, the same names on variables prevent it from compiling.

Working example even if the file exists:

#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);
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top