Open () read () write () Close () lseek () function in Linux

Source: Internet
Author: User

1. open () function

Function Description: Used to open or create a file. When opening or creating a file, you can specify the file attributes and user permissions.

Required header file: # include <sys/types. h>, # include <sys/STAT. h>, # include <fcntl. h>

Function prototype: int open (const char * pathname, intflags, int perms)

Parameters:

Pathname: name of the opened file (including the path name such as "DEV/ttys0 ")

Flags: file opening method,

O_rdonly: open a file in read-only mode

O_wronly: open the file in write-only mode

O_rdwr: open a file in read/write mode

O_creat: if the file to be modified does not exist, create a new file and set its permissions with the third parameter.

O_excl: if the object exists when o_creat is used, an error message is returned. This parameter can be used to test whether the file exists. In this case, open is an atomic operation to prevent multiple processes from creating the same file at the same time.

O_noctty: When this parameter is used, if the file is a terminal, the terminal will not be the control terminal of the process that calls open ().
O_trunc: if the file already exists, all original data in the file will be deleted and the file size is set to 0.
O_append: open a file by adding the file. When the file is opened, the file Pointer Points to the end of the file to add the written data to the end of the file.

O_nonblock: If pathname refers to a FIFO, a special block file, or a special character file, this option sets the non-blocking mode for this file's current open operation and subsequent I/O operations.

O_sync: enables each write operation to wait until the physical I/O operation is completed.
O_rsync: Read is performed after all write operations in the same region are completed.
In the open () function, falgs parameters can be combined with "|", but the first three standard constants (o_rdonly, o_wronly, and o_rdwr) cannot be combined with each other.

Perms: the access permission of the opened file, which can be expressed in two ways. A set of macros can be defined: s_ I (R/W/X) (usr/GRP/oth ), r/W/X indicates the read/write permission,

Usr/GRP/oth indicate the owner of the file, the group to which the file belongs, and other users, such as s_iruur | s_iwuur | s_ixuur, (-Rex ------). The same permission can also be indicated by October 800.

Return Value:

Success: The file descriptor is returned.

Failed:-1 is returned.

 

2. Close () function

Function Description: Used to close an opened file.

Required header file:# Include <unistd. h>

Function prototype: int close (int fd)

Parameter: FD file descriptor

Function return value: 0 success,-1 error

 

 

3. Read () function

Function Description: reads data from a file.
Required header file:# Include <unistd. h>

Function prototype: ssize_t
Read
(Int fd, void * Buf, size_t count );

Parameters: 
FD:Description of the file to be read.
Buf: refers to the buffer zone where the read data is stored.
Count: the number of characters that should be read when a read operation is called.

Returned value: the number of bytes read; 0 (read EOF);-1 (error ).

In the following cases, the number of bytes read is smallerCount:

   A. It is not enough to read the end of a common file.Count bytes. For example, if the file is only 30 bytes, we want to read 100
In bytes, only 30 bytes are actually read, and the READ function returns 30. Then, if you use the READ function to act on this file, the read will return 0.
 B. When reading data from a terminal device, generally only one row can be read at a time.
 C. When reading data from the network, the network cache may cause the number of bytes to be read to be smaller than count.
 D. When reading pipe or FIFO, the number of bytes in pipe or FIFO may be lessCount.
 E. When reading from a record-oriented device, some record-oriented devices (such as tapes) can only return one record at a time.
 F. The signal is interrupted when some data is read.
The read operation starts with CFO. CFO increases before the result is returned, and the increment is the number of bytes actually read.

 

4. Write () function

Function Description: write data to a file.
Required header file:# Include <unistd. h>

Function prototype: ssize_t write (int fd, void * Buf, size_t count );

Returned value: number of bytes written to the file (successful);-1 (error)

Function: The Write function writes data to filedes.Count byte data. The data source is Buf. The returned value is always equal to count. Otherwise, an error occurs. A common error occurs when the disk space is full or exceeds the file size limit.

For common files, the write operation starts with CFO. If o_append is used to open a file, data is written to the end of the file in each write operation. After successful writing, the CFO increases and the increment is the number of bytes actually written.

5. lseek () function 

Function Description: used to locate the file pointer in the specified file descriptor.
Required header file:# Include <unistd. h>, # include <sys/types. h>

Function prototype: off_t lseek (int fd, off_t offset, int whence );

Parameters:

FD; file descriptor

Offset: the offset. The distance to be moved for each read/write operation. The unit is byte. It can be positive or negative (forward or backward)

Whence:

Seek_set: the current position starts with the file, and the new position is the offset size.

Seek_cur: The current position is the pointer position, and the new position is the offset added to the current position

Seek_end: The current position is the end of the file. The new position is the file size plus the offset.

Return Value:

Success: the current displacement is returned.

Failed:-1 is returned.

6. Function instances

# Include <string. h>

# Define buffer_size128 // the size of each read/write cache, affecting the running efficiency
# Define src_file_name "src_file.txt" // source file name
# Define dest_file_name "dest_file.txt" // target file name
# Define offset0 // file pointer offset

Int main ()
{
Intsrc_file, dest_file;
Unsigned char src_buff [buffer_size];
Unsignedchar dest_buff [buffer_size];
Int real_read_len = 0;
Char STR [buffer_size] = "This Is A testabout \ nopen () \ nclose () \ nwrite () \ nread () \ nlseek () \ nend of thefile \ n ";
// Create a source file
Src_file = open (src_file_name, o_rdwr | o_creat, s_irusr | s_iwusr | s_irgrp | s_iroth );
If (src_file <0)
{
Printf ("Open File Error !!! \ N ");
Exit (1 );
}
// Write data to the source file
Write (src_file, STR, sizeof (STR ));
// Create the target file
Dest_file = open (dest_file_name, o_rdwr | o_creat, s_irusr | s_iwusr | s_irgrp | s_iroth );
If (dest_file <0)
{
Printf ("Open File Error !!! \ N ");
Exit (1 );
}

Lseek (src_file, offset, seek_set); // move the read/write pointer of the source file to the starting position
While (real_read_len = read (src_file, src_buff, sizeof (src_buff)> 0)
{
Printf ("src_file: % s", src_buff );
Write (dest_file, src_buff, real_read_len );
}
Lseek (dest_file, offset, seek_set); // move the read/write pointer of the target file to the starting position
While (real_read_len = read (dest_file, dest_buff, sizeof (dest_buff)> 0); // read the content of the target file
Printf ("dest_file: % s", dest_buff );

Close (src_file );
Close (dest_file );
Return 0;
}

The result is as follows:
Src_file: this is a test about
Open ()
Close ()
Write ()
Read ()
Lseek ()
End of the file
Dest_file: this is a test about
Open ()
Close ()
Write ()
Read ()
Lseek ()
End of the file

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.