-1

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
    Could you give us the error message you get ? – Thomas W. Dec 08 '16 at 10:51
  • 2
    You don't check if the `open` succeeded and you don't output the specific error. That makes debugging impossible. – David Schwartz Dec 08 '16 at 10:53
  • Segmentation fault. I think I am trying to access a file that I haven't created, but I do not want to do that, I want to actually generate it. – Eduardo Ramos Dec 08 '16 at 10:54
  • The thing is that I am not trying to open it, I want to create it. I just do not know how to. – Eduardo Ramos Dec 08 '16 at 10:55
  • Accept my edit don't copy and paste... I take time to indent your code! http://stackoverflow.com/review/suggested-edits/14534511 – Stargateur Dec 08 '16 at 10:58
  • Check if `open` returns -1 which indicates that the file could not be opened and if yes, then don't proceed any further but display an error message. If you want to create a file, then maybe you need [`creat`](http://man7.org/linux/man-pages/man2/creat.2.html). BTW there is no such thing as an _int file_. – Jabberwocky Dec 08 '16 at 11:07

1 Answers1

0

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);
}
Barmar
  • 741,623
  • 53
  • 500
  • 612