How to create an int file

315 views Asked by At

I am trying to create a shared file, which has to be int.

int f;

However, when I reach

if ((fstat(f, &stbuf) != 0) || (!S_ISREG(stbuf.st_mode)))

It gives me an error. The file must contain a string like:

abcd

My guess is the following, but it does not work:

int main() {
  int f;
  void *memoria = NULL;
  int tam;
  struct stat stbuf;
  char string[15] = {0};

  f = open("fichero.txt", O_RDWR, S_IRUSR);

  // ERROR IS HERE!!
  if ((fstat(f, &stbuf) != 0) || (!S_ISREG(stbuf.st_mode))) {
    printf("Error");
  }

  tam = stbuf.st_size;
  printf("%d\n", tam);

  // Proyect the file
  memoria = mmap(0, tam, PROT_WRITE, MAP_SHARED, f, 0);
  // Copy the string into the file
  memcpy(memoria, "abcd", 5);

  munmap(memoria, tam);

  return 0;
}

Should I change the parameters in open?? What am I doing wrong? Thanks!

1

There are 1 answers

7
Barmar On BEST ANSWER

You need to use the O_CREAT mode to create the file if it doesn't exist.

f = open("fichero.txt", O_RDWR | O_CREAT, S_IRUSR);

You should check for errors from open():

if (f == -1) {
    perror("open");
    exit(1);
}