Reputation: 16436
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
Upvotes: 1
Views: 11888
Reputation: 409442
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 toopen()
with flags equal toO_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.
Upvotes: 15
Reputation: 597
In early versions of the UNIX System, the second argument to open could be only 0, 1, or 2. There was no way to open a file that didn't already exist. Therefore, a separate system call, creat, was needed to create new files.
Note that:
int creat(const char *pathname, mode_t mode);
is equivalent to:
open(pathname, O_WRONLY|O_CREAT|O_TRUNC, mode);
Upvotes: 2