Linux open () function practice __oracle

Source: Internet
Author: User

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;

}


Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.