"creat" System Call in Unix

12,227

creat only creates a file if it doesn't exist. If it already exists, it's just truncated.

creat(filename, mode);

is equivalent to

open(filename, O_WRONLY|O_CREAT|O_TRUNC, mode);

And as specified in the open(2) documentation:

O_CREAT
If the file does not exist it will be created.

Share:
12,227
mohangraj
Author by

mohangraj

Updated on June 28, 2022

Comments

  • mohangraj
    mohangraj almost 2 years

    I am using creat system call to creat a file. The following is the program to creat a file

    #include<stdio.h>
    #include<fcntl.h>
    void main()
    {
        int fd=creat("a.txt",S_IRWXU|S_IWUSR|S_IRGRP|S_IROTH);
        printf("fd  = %d\n",fd);
    }
    

    So, At first time, the program creates a file named a.txt with appropriate permission. If I execute a.out one more time, the new a.txt will be created. But, the inode of the file remains same. How, it will be.

    $ ./a.out
    fd  = 3
    $ ls -li a.txt
    2444 -rw-r--r-- 1 mohanraj mohanraj 0 Aug 27 15:02 a.txt
    $ cat>a.txt
    this is file a.txt
    $ ./a.out
    fd  = 3
    $ cat a.txt
    $ls -li a.txt
    2444 -rw-r--r-- 1 mohanraj mohanraj 0 Aug 27 15:02 a.txt
    $
    

    In the above output, a.txt have the content as "This is file a.txt". Once I execute the a.out, the new a.txt created. But, the inode 2444 remains same. So, how creat system call works?

    Thanks in advance.