简体   繁体   中英

How to create an int file

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!

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM