Linux-based I/O operations

Source: Internet
Author: User
Tags flock format definition fread

Linux file I/O programming Linux files and file descriptors introduction
    • Operations on directories and lovemaking in Linux are equivalent to file operations
    • There are 4 main types of files in Linux: Normal files, directory files, connection files, and device files
    • Under Linux, all operations on devices and files are performed using file descriptors.
    • Start of a process, typically with three files open: standard input (Stdin_fileno), standard output (Stdout_fileno), standard error (Stderr_fileno)
Basic I/O operation functions--without caching:
  • Open, read, write, Lseek, and close

    • Open, close function

      • open function for opening or creating a file, you can specify properties
      • close function to close open file
      • Syntax format:

         
                 
                   header files: #include <sys/types.h> #include <sys/stat.h> #include <fcntl.h> #include <unistd.h>  
                 
      • Open function:

          int open (const char *pathname, flags, int perms);p athname: file name opened ( Can include a path) flag (open mode):(common way) O_rdonly: Read-only mode o_wronly: Writable O_RDWR: Read and write mode o_create: If the file does not exist, create a new file and set the permissions for it with the third parameter-- ------------------------------o_excl: Used to test whether a file exists O_trunc: If the file already exists and is opened successfully with read-only or write-only, the original data in the file is deleted o+append: Open the text as added When open, the file pointer points to the end of the file perms: Access to the Open file, the 8 Forbidden notation Flag parameter can be passed by "|" Join multiple combined form return value: Return file descriptor successfully, failed return-1  
      • Close function:

          int close (int fd); FD: File Descriptor return value: successfully returned 0 , failed to return-1  
    • Such as: mathod_01.c

        #include <sys/types.h> #include <unistd.h> #include <sys/stat.h     > #include <fcntl.h> #include <stdlib.h> #include <stdio.h>int main (void) {int fd; Define the file descriptor//Call the Open function to open in a read-write manner, using the "|" Symbolic link if ((Fd=open ("/home/my/mytest.c", O_create | O_trunc |    O_rdwr, 0666)) < 0) {perror ("open:");    Print error message exit (1);    }else{//Note: The file descriptor returned by the Open function must be the smallest unused file descriptor printf ("Open file:mytest.c%d\n", FD);        } if (Close (FD) <0) {perror ("close:");    Exit (1);    }else{printf ("Close mytest.c\n"); } exit (0);  
    • Read, write, and Lseek functions

      • function:
        • read: Reads data from the specified file descriptor
        • write: Used to write data to an open file, write The operation starts at the current offset of the file and is exceeded returns the
        • Lseek: Used to position the file pointer to the appropriate location in the specified file descriptor
      • Syntax format:

        • Header file

            #include <unistd.h> #include <sys/types.h>  
        • Read function

            ssize_t Read (int fd, void *buf, size_t count); FD: File descriptor buf: Specifies the buffer of the memory readout data count: Specifies the number of bytes read out return value: The number of bytes read successfully returned, 0 for the end of the file; 1 for error  
        • Write function

            ssize_t Write (int fd, void *buf, size_t count), FD: File descriptor buf: Specifies the buffer in which the memory is written to count: Specifies the number of bytes written to return a value: succeeded, returns the number of bytes written; failed, returned-1  
        • Lseek function

            off_t lseek (int fd, off_t offset, int whence); FD: File descriptor offset: offset, per read and write The distance that the operation needs to be moved, in units of bytes. Positive (forward) whence (base point at current position): Seek_set: The current position is the beginning of the file, the new position is a low-cost size seek_cur: The current position is the position of the file pointer, the new position is the current position plus the offset seek_end: The current position is the file's At the end, the new position returns the value of the file plus the size of the offset: succeeds, returns the current offset; 1  
    • such as: method_02.c

      #include <unistd.h> #include <sys/types.h> #include <sys/stat.h> #include <fcntl.h> #include    <stdlib.h> #include <stdio.h> #include <string.h> #define Maxsizeint main (void) {int I, FD, size, Len; Char *buf = "hello!    Welcom to Linux world! ";    Char buf_read[10];    Len = strlen (BUF); Open the file and set permissions if (FD = open ("/home/my/mytest.c", O_creat | O_trunc |        O_RDWR, 666)) < 0) {perror ("Open:");    Exit (1);                     }else{printf ("Open file:mytest.c\n", FD);        The//write function writes the contents of the BUF to the open file if (size = Write (FD, buf, Len)) < 0) {perror ("write:");    Exit (1);    }else{printf ("write:%s\n", buf);    }//Call the Lseek function to move the pointer and call read Read file Lseek (FD, 0, Seek_set);        if (size = Read (FD, Buf_read, ten)) < 0) {perror ("read:");    Exit (0);    }else{printf ("read from file:%s\n", buf_read);        }//Closes Close () if (Close (FD) < 0) {perror ("close:");    Exit (1); }else{        printf ("Close mytest.c\n"); } exit (0);}
  • Fcntl function: Properties of the action file descriptor

    • function format

      • Header file

        #include <sys/types.h>#include <unistd.h>#include <fcntl.h>
      • Function Prototypes:

        int fcntl(int fd, int cmd, struct flock *lock);fd:文件描述符cmd:(常见的有以下几个)    F_DUPFD:复制文件描述符    F_GETFL:得到open设置的标志    F_SETFL:改变open设置的标志    F_GETTFK:根据lock描述,决定是否上文件锁    F_SETFK:设置lock描述的文件锁    F_SETOWN:设置进程号或进程组号lock:设置记录锁的具体状态    lock的结构:        struct flock{            short l_type;       //取值:F_RDLCK(读取锁→共享锁)、F_WRLCK(写入锁→排斥锁)、F_UNLCK(解锁)            short l_start;      //相对位移量(字节)            short l_whence;                 off_t l_len;        //加锁区域长度            pid_t l_pid;        }返回值:成功,返回0,;失败返回-1
Standard I/O development-based buffering
  • Objective:
    Reduce the number of use of read and write calls
  • Three types of buffered storage:
    • Full buffer
      The actual I/O operation is not performed until the standard I/O cache is filled.
    • Row buffers
      The standard I/O library performs I/O operations when the input and output have new line characters.
    • With no buffering
      Do not buffer characters, such as: can display error message as soon as possible
  • Open and Close files

    • Open the file standard function: fopen, Fdopen, Freopen, returns a pointer to files
      • fopen: Specifies the path and mode of the open file
      • Fdopen: Specifies that open file description conforms to mode
      • Freopen: Can specify open file, mode, specify specific IO stream
    • function format definition

      • Header file

        #include<stdio.h>
      • fopen, Fdopen, Freopen

        FILE* fopen(const char* path, const char* mode);FILE* fdopen(int fd, const char* mode);FILE* freopen(const char* path, const char* mode, FILE* stream);path:包含要打开的文件的路径及文件名fd:要打开的文件描述符mode:文件打开状态,取值:    r/rb:打开只读文件,文件必须存在    r+/r+b:打开可读写文件,文件必须存在    w/wb:打开只写文件,覆盖的方式(会清空存在的文件内容)    w+/w+b:打开可读写文件,覆盖的方式    a/ab:附加的当时打开只写文件,添加方式(在文件内容后添加内容)    a+/a+b:附加的当时打开读写文件,添加方式stream:已打开的文件指针返回值:成功,返回指向FILE的指针,失败返回NULL
    • Close file function: fclose

      • Function: Data within the buffer is written to the file, and the file resource is freed
      • Format:

        int fclose(FILE* stream);stream:已打开的文件指针返回值:成功:0,失败:EOF
    • Such as:

      #include<stdio.h>int main(void){    FILE *fp;    //调用fopen函数    fp = fopen("/home/test/hello.c", "w");    if(fp != NULL){        printf("Open Success!");    }    //关闭文件指针    fclose(fp);}
  • Reading and writing of files

    • Header file:

      #include <stdio.h>
    • Read file: fread function

      • Format:

        size_t fread(void *ptr, size_t size, size_t nmemb, FILE *stream);ptr:存放读入记录的缓冲区size:读取的记录大小nmemb:读取的记录数stream:要读取的文件流返回值:成功,返回实际读到的nmemb,失败返回EOF
    • Write File: fwrite function

      • Format

        size_t fwrite(const void *ptr, size_t size, size_t nmemb, FILE *stream);ptr:存放写入记录的缓冲区size:写入的记录大小nmemb:写入的记录数stream:要写入的文件流返回值:成功,返回实际写入的nmemb数目,失败返回EOF
    • Such as:

      #include <stdio.h>int main(void){    FILE *stream;    char str[5] = {‘H‘, ‘e‘, ‘l‘, ‘l‘, ‘o‘};    //先打开文件    stream = fopen("test", "w");    int number = fwrite(str, sizeof(char), nmemb, stream);    printf("number = %d", number);    //关闭文件流    fclose(stream);}

Linux-based I/O operations

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.