繁体   English   中英

如何创建一个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);
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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