如何创建一个int文件

How to create an int file

我正在尝试创建一个共享文件,它必须是 int。

int f;

然而,当我到达

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

它给我一个错误。该文件必须包含如下字符串:

abcd

我的猜测如下,但它不起作用:

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

我应该在打开时更改参数吗?? 我究竟做错了什么?谢谢!

如果文件不存在,您需要使用O_CREAT模式创建。

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

您应该检查来自 open() 的错误:

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