cunixfile-io

What is the difference between open and creat system call in c?


I tried both creat and open system call. Both working in the same way and I can't predict the difference among them. I read the man page. It shows "Open can open device special files, but creat cannot create them". I dont understand what is a special file.

Here is my code,

I am trying to read/write the file using creat system call.

#include<stdio.h>
#include<fcntl.h>
#include<sys/types.h>
#include<sys/stat.h>
#include<unistd.h>
#include<errno.h>
#include<stdlib.h>
int main()
{
 int fd;
 int written;
 int bytes_read;
 char buf[]="Hello! Everybody";
 char out[10];
 printf("Buffer String : %s\n",buf);
 fd=creat("output",S_IRWXU);
 if( -1 == fd)
 {
  perror("\nError opening output file");
  exit(0);
 }

 written=write(fd,buf,5);
 if( -1 == written)
 {
  perror("\nFile Write Error");
  exit(0);
 }
 close(fd);
 fd=creat("output",S_IRWXU);

 if( -1 == fd)
 {
  perror("\nfile read error\n");
  exit(0);
 }
 bytes_read=read(fd,out,20);
 printf("\n-->%s\n",out);
 return 0;
}

I expted the content "Hello" to printed in the file "output". The file created successfully. But content is empty


Solution

  • The creat function creates files, but can not open existing file. If using creat on an existing file, the file will be truncated and can only be written to. To quote from the Linux manual page:

    creat() is equivalent to open() with flags equal to O_CREAT|O_WRONLY|O_TRUNC.

    As for device special files, those are all the files in the /dev folder. It's simply a way of communicating with a device through normal read/write/ioctl calls.