1, first Use Man 2 open to view the Open function interface
2, the simplest open function code
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <stdio.h >
int Main ()
{
int fd;
Fd=open ("abc", o_creat,0777);
printf ("fd=%d\n", FD);
return 0;
}
3, open () a file, the return of the file descriptor starting from 3, parameter o_creat means that when "ABC" does not exist, create one, but because Umask first is 002, so the permission created is not 777, but 775, Set the Umask to 000 and then perform the creation of the ABC's permission bit is 777.
4. Pass a parameter when open
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include < stdlib.h>
#include <stdio.h>
int main (int argc,char *argv[])
{
int fd;
if (argc<2) {
printf ("./open filename\n");
Exit (1);//<stdlib.h>
}
fd=open (argv[1],o_creat,0644);
printf ("fd=%d\n", FD);
return 0;
}
4, open () a file, do not exist to create a, and to write something in the file
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include < stdlib.h>
#include <stdio.h>
#include <unistd.h>
#include <string.h>
int main (int argc,char *argv[])
{
int fd;
Char buf[1024]= "Hello Tengfei";
if (argc<2) {
printf ("./open filename\n");
Exit (1);//<stdlib.h>
}
fd=open (Argv[1],o_creat | o_rdwr,0644);
Write (Fd,buf,strlen (BUF));
printf ("fd=%d\n", FD);
Close (FD);
return 0;
}