Read and write operations for files under Linux (Openreadwrite)

Source: Internet
Author: User
Tags define function file copy function prototype readable

Read and write operation of files under Linux (openreadwrite)
turn http://www.2cto.com/os/201403/285837.html

open (opens file)
Correlation function Read,write,fcntl,close,link,stat,umask,unlink,fopen
Table header file #include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
Defines the function int open (const char * pathname, int flags);
int open (const char * pathname,int flags, mode_t mode);

The function description parameter pathname points to the file path string that you want to open. The following are the flags that the parameter flags can use:
O_rdonly opening a file as read-only
O_wronly opening a file as a write-only method
The O_rdwr opens the file in a writable and writable manner. The above three kinds of flags are mutually exclusive, that is, cannot be used simultaneously, but can be used with the following flags or (|) operator combinations.
O_creat If the file you want to open does not exist, the file is created automatically.
O_excl If O_creat is also set, this command checks to see if the file exists. The file is created if it does not exist, otherwise it will cause an open file error. In addition, if O_creat and O_EXCL are set simultaneously and the file to be opened is a symbolic connection, the file will fail to open.
O_noctty If the file you want to open is a terminal device, the terminal is not treated as a Process control terminal.
O_trunc if the file exists and opens in a writable manner, this flag bidding clubs the file length to 0, and the data originally stored in the file disappears.
O_append when a file is read and written, it moves from the end of the file, which means that the data is appended to the file after it is added.
The O_nonblock opens the file in an unstoppable way, that is, whether or not data is read or waiting, it will be returned to the process immediately.
O_ndelay with O_nonblock.
O_sync Open the file in a synchronized manner.
O_nofollow if the file referred to by the parameter pathname is a symbolic connection, the open file will fail.
O_directory if the file that the parameter pathname refers to is not a directory, the open file fails.
This is a special flag after Linux2.2 to avoid some system security problems. The parameter mode has the following combinations, which will only take effect when a new file is created, and the permissions of the real file will be affected by the umask value, so the file permission should be (Mode-umaks).
s_irwxu00700 permission that represents the file owner with readable, writable, and executable permissions.
S_IRUSR or s_iread,00400 permission that represents the owner of the file with readable permissions.
S_IWUSR or S_IWRITE,00200 permission that represents the file owner with writable permissions.
A s_ixusr or S_IEXEC,00100 permission that represents the owner of the file that has executable permissions.
S_IRWXG 00070 permission, which represents the file user group with readable, writable, and executable permissions.
S_IRGRP 00040 permission, which represents the file user group with readable permissions.
S_IWGRP 00020 permission, which represents the file user group with writable permissions.
S_IXGRP 00010 permissions, which represent the permissions that the file user group has to perform.
S_irwxo 00007 permissions, which represent other users with readable, writable, and executable permissions.
S_iroth 00004 permissions, with readable permissions on behalf of other users
S_iwoth 00002 permissions, which represent other users with writable permissions.
S_ixoth 00001 permissions, which represent other users with enforceable permissions.

Return value returns a value of 0 if all the permissions to be checked are passed, indicating success, or 1 if one of the permissions is disabled.


Read (reading data from an open file)
Correlation function Readdir,write,fcntl,close,lseek,readlink,fread
Table header file #include <unistd.h>
Defines the function ssize_t read (int fd,void * buf, size_t count);
The function description Read () transfers the file referred to by the parameter fd to count bytes to the memory referred to by the BUF pointer. If the parameter count is 0, then read () does not function and returns 0. The return value is the number of bytes actually read, and if 0 is returned, indicating that the end of the file is reached or that no readable data is available, and that the file read and write location moves with the bytes read.

Additional instructions if smooth read () will return the actual number of bytes read, it is better to compare the return value with the parameter count, if the number of bytes returned is less than the number of bytes required to read, it is possible to read the end of the file, read from the pipe (pipe) or terminal, or read () is interrupted by the read action. Returns 1 when an error occurs, the error code is stored in errno, and the file read-write location cannot be expected.

Error code EINTR This call was interrupted by the signal.
Eagain when non-blocking I/O is used (o_nonblock), this value is returned if no data is readable.
EBADF parameter FD is not a valid file descriptor, or the file is closed.

Example reference open ().

Sync (write buffer data back to disk)
Correlation function Fsync
Table header file #include <unistd.h>
define function int sync (void)
The function Description Sync () is responsible for writing the system buffer data back to disk to ensure data synchronization.
The return value returns 0.

Write (writes data to an open file)
Correlation function Open,read,fcntl,close,lseek,sync,fsync,fwrite
Table header file #include <unistd.h>
Defines the function ssize_t write (int fd,const void * buf,size_t count);
The function description Write () writes the memory referred to by the parameter buf to count bytes to the file referred to by the parameter FD. Of course, the file read and write location will also move with it.
The return value if smooth write () returns the number of bytes actually written. Returns 1 when an error occurs, and the error code is stored in errno.
Error code EINTR This call was interrupted by the signal.
Eagain when non-blocking I/O is used (o_nonblock), this value is returned if no data is readable.
EADF parameter FD is not a valid file descriptor, or the file is closed.
For example, please refer to open ().

Lseek for file location positioning

int fd = open (file_name,o_rdonly);
if (fd<0) return-1;
Long fsize = Lseek (fd,0l,seek_end);
Close (FD);

Lseek for file location positioning
Function prototype: off_t lseek (int fildes, off_t offset, int whence);

Fildes, which represents the open file descriptor
Offset, which indicates the relative amount that the operation needs to be moved
whence, indicating the direction of file movement
There are three types of values:
Lseek (int fildes, off_t offset, seek_set);
The return value is the offset position after the beginning of the file, and the start of seek is the file header
Lseek (int fildes, off_t offset, seek_cur);
The return value is the value +offset the current offset of the file, and the start position of seek is the current position
Lseek (int fildes, off_t offset, seek_end);
The return value is the file size +offset,seed The starting position is the end of the file
[offset can be positively negative, indicating the relative position of the relationship]

Offset offsets bytes are units. The return value in the case of a successful call represents the file read offset relative to the file header
Returns 1 in the event of a call failure


Lseek records the current file offset in the kernel and does not cause any actual I/O operations, and subsequent file read/write operations will be performed at that offset. Writes to the file will cause a hole in the file if the file offset is greater than the file's current length. That is, the segment of the displacement that has not been written bytes is read as 0.

Therefore, it is more efficient to find the file size, as shown in the previous program fragment:

Long fsize = Lseek (fd,0l,seek_end);
Offsize parameter = 0;
whence = Seek_end;
The return value is the file size.

Test code:

[email protected]:/home/wl/Desktop/c++# cat-n file_copy.cpp 1 2#include <stdio.h> 3#include <string .h> 4#include <stdlib.h> 5#include <sys/types.h> 6#include <sys/stat.h> 7#include &lt ;unistd.h> 8#include <fcntl.h> 9#define buffer_size 1024 10 11/* 12 * Program Entry * */14int M    Ain (int argc,char **argv) 15{int from_fd, TO_FD;    File_len=0 long;    Ret=1 int;    + Char buffer[buffer_size];    Char *ptr;    21 22/* Determine the entry * * (argc!=3) ("usage:%s fromfile tofile\n", argv[0]);    + exit (1); 27} 28 29/* Open source file * * (From_fd=open (argv[1], o_rdonly|     o_creat)) (==-1) ("Open%s error\n", argv[1]);     Exit (1); 34} 35 36/* Create destination file */PNS (To_fd=open (argv[2], o_wronly| O_creat) ==-1) ("Open%s error\n", argv[2]);     + exit (1);    41} 42 43 * * Measured file size */file_len= Lseek (from_fd,0l,seek_end);    Lseek (From_fd,0l,seek_set);    * printf ("form file size is%d\n", File_len);    47 48/* File copy * * (ret) {ret= read (from_fd, buffer, buffer_size);     Ret==-1 ("read error\n");    -Exit (1);    (TO_FD, buffer, ret);    File_len-=ret;    Bzero (buffer,buffer_size);    ("There is%d byte (s) data left without copy\n", File_len);     Close (FROM_FD);     Close (TO_FD);     Exit (0); The 67[email protected]:/home/wl/table/c++# g++ file_copy.cpp-o file_copyfile_copy.cpp: in function ' int main (int, char * *) ' in: file_copy.cpp:46:45: Warning: Format '%d ' expects argument of type ' int ', but argument 2 have type ' long int ' [-wformat]file_c OPY.CPP:61:69: Warning: Format '%d ' expects argument of TyPE ' int ', but argument 2 have type ' long int ' [-wformat][email protected]:/home/wl/desktop/c++# vim file_copy.cpp[email&nb sp;protected]:/home/wl/desktop/c++#./file_copy file_copy.cpp test.cppform file size is 1348there be 0 byte (s) data left wit Hout copy[email protected]:/home/wl/Desktop/c++# diff file_copy.cpp test.cpp [email protected]:/home/wl/Desktop/c++  #

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.