Linux File operating system call

Source: Internet
Author: User
Tags lstat

In linux, everything is a file. Files provide a simple and unified interface for operating system services and devices, which means that programs can use various devices as they use files. In most cases, only open, write, lseek, read, and close systems are used for file operations. This article uses a simple example to introduce these five calls and their associated content.

First look at the example:
>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> >>>>>>>>>>>>
# Include <unistd. h>
# Include <stdlib. h>
# Include <stdio. h>
# Include <fcntl. h>
# Include <sys/types. h>
# Include <sys/stat. h>
# Include <string. h>

Int
Main (void)
{
Int file_des = open ("my_file.txt", O_RDWR | O_CREAT | O_EXCL, S_IRUSR | S_IWUSR | S_IXUSR | S_IXOTH );
 
Char * write_buf = "zhujiangfeng \ n ";
If (write (file_des, write_buf, strlen (write_buf ))! = Strlen (write_buf ))
{
Write (STDERR_FILENO, "write error! \ N ", 13 );
Exit (0 );
}

If (lseek (file_des, 4, SEEK_END) =-1)
{
Write (STDERR_FILENO, "seek error! \ N ", 11 );
Exit (0 );
}
Write (file_des, "AAAAAA", 6 );

Lseek (file_des, 0, SEEK_SET );
Char read_buf [50];

If (read (file_des, read_buf, 50) =-1)
{
Write (STDERR_FILENO, "read error! \ N ", 12 );
Exit (0 );
}
Write (STDOUT_FILENO, read_buf, 50 );

Close (file_des );
Exit (1 );
}
>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> >>>>>>>>>>>>>>>>>>>>>>
This is a simple example of reading and writing files. First, create a text file, write some content, and then output the text content to the standard output. The following is an example:
1 int file_des = open ("my_file.txt", O_RDWR | O_CREAT | O_EXCL, S_IRUSR | S_IWUSR | S_IXUSR | S_IXOTH );
Open a new file my_file.txt in read/write mode and specify its access permission as the read, write, and execute permissions for the file owner. group users do not have any permissions, and other users only have the execution permission.

An open call is used to create or open a file and return a file descriptor.
# Include <fcntl. h>
# Include <sys/stat. h>
# Include <sys/types. h>
Int open (const char * path, int oflags );
Int open (const char * path, int oflags, mode_t mode );

The first oen is used to open an existing file, and the second open is used to create a new file.
(1) The oflags parameter describes how to open a file. The value is the "or" Operation of one or more constants (these constants are defined in <fcntl. h> ):
O_RDONLY read-only
O_WRONLY write-only open
O_RDWR read, write open
The preceding constants are required and can only be selected. The following constants are optional:
Append O_APPEND to the end of the file
O_TRUNC truncates the file length to 0
If the object does not exist in O_CREATE, create an object based on the access permission specified by the mode parameter.
O_EXCL is used with O_CREATE to test whether the file to be created exists. This makes the test and creation of the file a yard operation.
(2) the mode parameter specifies the access permission for the new file. The value is the "or" operation with one or more identifiers (these identifiers are defined in <sys/stat. h> ):
S_IRUSR file owner has read permission
S_IWUSR file owner has write permission
S_IXUSR file owner has execution permission
 
S_IRGRP file group has read permission
S_IWGRP file group has write permission
S_IXGRP file group has execution permission

S_IROTH other users have read permission
S_IWOTH other users have write permission
S_IXOTH other users have execution Permissions
Note: The mode parameter is actually a request for setting file access permissions. whether the request is allowed depends on the umask setting.
(3) If two programs open the same file at the same time, two different file descriptors will be obtained. If both write operations are performed, their data will be overwritten, rather than intertwined. The two files have their own understanding of the starting position (offset value) of the read and write operations. The file lock can prevent this situation and will be mentioned later.

2 write (file_des, write_buf, strlen (write_buf ))! = Strlen (write_buf)
Write all the bytes in the buffer write_buf to the file associated with the file descriptor file_des, and determine whether the write is successful.

# Include <unistd. h>
Size_t write (int file_des, const void * buf, size_t bytes );

(1) the return value of write may be smaller than bytes, but this is not necessarily an error. Check the global variable errno to determine.

3 if (lseek (file_des, 4, SEEK_END) =-1)
{
Write (STDERR_FILENO, "seek error! \ N ", 11 );
Exit (0 );
}
Push the read/write offset of the file to four bytes above the end of the file. If the file fails, it is like the standard output error message.

# Include <unistd. h>
# Include <sys/types. h>
Off_t lseek (int file_des, off_t off_set, int whence );
Lseek is used to set the read/write offset of a file and return the new read/write offset.

(1) off_t is an implementation-related type, which is defined in <sys/types. h>;
(2) The value of whence is as follows:
SEEK_SET sets the file's read/write offset to off_set bytes from the start of the file.
SEEK_CUR sets the file read/write offset to the current value plus off_set, and off_set can be positive or negative.
SEEK_END sets the file read/write offset to the file length plus off_set, and off_set can be positive or negative.
(3) When it is written after the end of the file is exceeded, an empty space is formed in the file. File holes do not occupy disk space. The processing method is related to the implementation of the file system. You can use $ od-c file to view the content of the empty file.
(4) STDIN_FILENO, STDOUT_FILENO, and STDERR_FILENO correspond to the standard input, output, and standard error respectively. These constants are defined in <unistd. h>.

4 # include <unistd. h>
Int close (int file_des );
Terminate the association between the file descriptor file_des and the corresponding file.

(1) The file descriptor is released and reused;
(2) After the file is closed, the process will release all record locks added to the file;
(3) After the process is terminated, the kernel automatically closes all open files.

5. Other file-related system calls
(1) # include <unistd. h>
# Include <sys/stat. h>
# Include <sys/types. h>
Int fstat (int file_des, struct stat * buf );
Int stat (const char * path, struct stat * buf );
Int lstat (const char * path, struct stat * buf );
These three system calls are used to obtain the information of the file and fill it in struct stat. 0 is returned for success, and-1 is returned for error. When path points to an object that is a symbolic link, stat returns information about the file to which the link points, and lstat returns information about the link. These three system calls will be discussed as a topic in the future.
(2) # include <unistd. h>
Int dup (int file_des );
Int dup2 (int file_des, int file_des2 );
The dup system calls the copy file descriptor file_des to return a new minimum available file descriptor. Two or more file descriptors can be used to read and write data in different locations of a file. Dup2 explicitly specifies to copy file_des to file_des2. This is useful for inter-process communication through pipelines.

Author: "mackerel"

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.