File I/O operations

Source: Internet
Author: User

1. open the file

# Include <fcntl. h>
Define the int open (const char * pathname, int flags) function );
Int open (const char * pathname, int flags, mode_t mode );
Function Description: The pathname parameter points to the file path string to be opened. The following are flags that can be used by the flags parameter:
O_rdonly open a file in read-only mode
O_wronly open the file in write-only mode
O_rdwr can open files in read/write mode.

The above three flags are mutually exclusive, that is, they cannot be used at the same time, but can be combined with the following flags using the OR (|) operator.
O_creat: if the file to be opened does not exist, the file is automatically created.
O_excl if o_creat is also set, this command checks whether the file exists. If the file does not exist, the file will be created; otherwise, the file will be opened incorrectly. In addition, if
O_creat and o_excl are set at the same time, and the file to be opened is a symbolic connection
Opening the file failed.
O_noctty if the file to be opened is a terminal device
Process control terminal.
If the o_trunc file exists and is opened in writable mode, this flag will clear the file length to 0, and the information originally stored in the file will also disappear.
O_append: when reading and writing a file, it will start to move from the end of the file, that is, the written data.
Will be appended to the end of the file.
O_nonblock open the file in an unblocking way, that is, whether there is data read or waiting, it will immediately return to the process.
O_ndelay is the same as o_nonblock.
O_sync opens the file in synchronous mode.
O_nofollow
Opening the file failed.
O_directory if the file indicated by the pathname parameter is not a directory
Opening the file failed.
This is a flag unique after linux2.2 to avoid some system security problems. Parameters
Mode has the following combinations, which take effect only when a new file is created. In addition, the permissions for creating a file are affected by the umask value, therefore, the file permission should be (Mode-umaks ).
S_irwxu00700 permission indicates that the object owner has the readable, writable, and executable permissions.
S_irusr, s_iread, and 00400 permissions indicate that the file owner has the readable permission.
S_iwusr or s_iwrite, 00200 permission, indicates that the file owner has the write permission
.
S_ixusr or s_iexec, 00100 permission indicates that the file owner has executable permission.
S_irwxg 00070 permission, which indicates that the file user group has the readable, writable, and executable permissions.
Permission.
S_irgrp 00040 permission indicates that the file user group has the readable permission.
S_iwgrp 00020 permission indicates that the file user group has the write permission.
S_ixgrp 00010 permission indicates that the file user group has executable permissions.
S_irwxo 00007 indicates that other users have the readable, writable, and executable permissions.
S_iroth 00004 permission, which indicates that other users have the readable permission
S_iwoth 00002 permission indicates that other users have the write permission.
S_ixoth 00001 permission indicates that other users have executable permissions.
Return Value: if all the permissions to be verified have passed the check, 0 is returned, indicating success. If one permission is disabled,-1 is returned.
The file indicated by the error code eexist parameter pathname already exists, but the o_creat and o_excl flag are used.
The file indicated by the eaccess parameter pathname does not meet the required permissions.
The file to be tested by erofs is stored in the read-only file system.
The pathname pointer of the efault parameter exceeds the accessible memory space.
The Mode Val parameter mode is incorrect.
The pathname parameter of enametoolong is too long.
The pathname parameter of enotdir is not a directory.
The enomem core memory is insufficient.
The pathname parameter of eloop has too many symbolic connections.
Eio I/O access error.
Note that you must be especially careful when using access () for user authentication. For example, making an open () empty file after access () may cause system security problems.

 

Example:

# Include <unistd. h>
# Include <sys/types. h>
# Include <sys/STAT. h>
# Include <fcntl. h>
Main ()
{
Int FD, size;
Char s [] = "Linux programmer! /N ", buffer [80];
FD = open ("/tmp/Temp", o_wronly | o_creat );
Write (FD, S, sizeof (s ));
Close (FD );
FD = open ("/tmp/Temp", o_rdonly );
Size = read (FD, buffer, sizeof (buffer ));
Close (FD );
Printf ("% s", buffer );
}

 

 

2. An error occurred while opening the file.

Check the errno variable.

 

Int FD = open (......);

If (FD =-1)

{

Perror ("fail to open ");

Exit (1 );

}

 

3. Close an object

 

# Include <unistd. h>

Int close (int fd );

 

Function Description: After a file is used, close () can be used to close the file if it is no longer needed,
Close () writes data back to the disk and releases the resources occupied by the file. The FD parameter is
The description of the file previously returned by open () or creat.
If the file is closed successfully, 0 is returned. If an error occurs,-1 is returned.
The error code is an invalid file description of the parameter FD (ebadf) or the file is closed.
Note: although the system will automatically close opened files at the end of the process, we recommend that you
Close the file and check the returned value.

 

 

4. Create a new file

 

# Include <fcntl. h>
Define the function int creat (const char * pathname, mode_tmode );
Function Description: The pathname parameter points to the file path string to be created. Creat () is equivalent to calling open () using the following call Methods ()
Open (const char * pathname, (o_creat | o_wronly | o_trunc ));
For error code about the parameter mode, see open () function.
If the return value is creat (), a new file description is returned. If an error occurs,-1 is returned, and the error code is set to errno.
The file specified by the eexist parameter pathname already exists.
The file specified by the eaccess parameter pathname does not meet the required permissions.
The file to which erofs wants to open the write permission exists in the read-only file system.
The pathname pointer of the efault parameter exceeds the accessible memory space.
The Mode Val parameter mode is incorrect.
The pathname parameter of enametoolong is too long.
The pathname parameter of enotdir is a directory.
Insufficient enomem core memory
The pathname parameter of eloop has too many symbolic connections.
Emfile has reached the maximum number of files that can be opened simultaneously by the process.
Enfile has reached the maximum number of files that can be opened simultaneously by the system.
Additional instructions creat () cannot create special device files. Use mknod () if necessary ().

 

Creat can only open new files in the write-only mode. If you want to perform a read operation, you need to close the file and use the read method to open it. Therefore, creat is rarely used.

 

 

 

5. File Location

Each opened file has a file offset, which is generally a non-negative certificate. All operations on the file, such as reading and writing, start at the offset of the current file, and increase the file offset.

By default, the offset of the opened file is 0. Use lseek to change the offset of the opened file.

 

# Include <unistd. h>
Define the off_t lseek function (INT Fildes, off_t offset, int whence );
Function Description: each opened file has a read/write location.
The position is to start with the file. If you open the file (such as o_append) as an attachment, the read/write position will point to the end of the file. When read () or write (),
Added. lseek () is used to control the read/write location of the file. The Fildes parameter is
Description of the opened file. The offset parameter is used to move the read/write Location Based on the whence parameter.
.
The whence parameter is one of the following:
The seek_set parameter offset is the new read/write location.
Seek_cur increases the offset displacement at the current read/write position.
Seek_end points the read/write position to the end of the file and then increases the offset displacement.
When the whence value is seek_cur or seek_end, The offet parameter allows negative output.
Now.
Here are some special instructions:
1) to move the read/write location to the beginning of the file: lseek (int
Fildes, 0, seek_set );
2) When you want to move the read/write location to the end of the file: lseek (INT Fildes,
0, seek_end );
3) to obtain the current file location: lseek (INT Fildes, 0, seek_cur );
Return value when the call is successful, the current read/write location is returned, that is, the number of bytes from the beginning of the file. If an error occurs,-1 is returned, and errno stores the error code.
Additionally, the Linux system does not allow lseek () to act on the tty device.
() Returns espipe.

 

 

// Lseek. c

# Include <stdio. h>
# Include <stdlib. h>
# Include <fcntl. h>
# Include <unistd. h>
# Include <errno. h>

# Deprecision Max 1024

Int main (void)
{
Int FD;
Off_t off;
Char Buf [Max];

FD = open ("test.txt", o_rdwr);/* open a file */
If (FD =-1 ){
Perror ("fail to open ");
Exit (1 );
}

Printf ("before reading/N");/* output prompt information */

Off = lseek (FD, 0, seek_cur);/* call the lseek function to obtain the read/write location of the current file */
If (Off =-1 ){
Perror ("fail to lseek ");
Exit (1 );
}

Printf ("the offset is: % d/N", off);/* output prompt */

If (read (FD, Buf, 5) =-1) {/* read 5 bytes of file content */
Perror ("fail ot read ");
Exit (1 );
}

Printf ("after reading/N");/* output prompt information */

Off = lseek (FD, 0, seek_cur);/* call the lseek function again to obtain the read/write location of the current file */
If (Off =-1 ){
Perror ("fail to lseek ");
Exit (errno );
}

Printf ("the offset is: % d/N", off);/* output result */

Close (FD);/* close the file */

Return 0;
}

 

 

 

6. File Truncation

 

# Include <unistd. h>

Int truncate (const char * pathname, off_t Len );

 

Len indicates the number of bytes to be truncated.

 

# Include <stdio. h>
# Include <stdlib. h>
# Include <unistd. h>
# Include <fcntl. h>

# Define Max 32

Int main (INT argc, char * argv [])
{
Int FD;
Int Len;
Int rest;
Int I;
Char Buf [Max];

If (argc! = 3) {/* set the number of extended file bytes and the number of bytes to be filled Based on the command line parameters */
Len = max;
Rest = 0;
} Else {
Len = atoi (argv [1]);
Rest = atoi (argv [2]);
}

If (truncate ("test.txt", max) =-1) {/* truncate the object to the specified number of bytes */
Perror ("fail to truncate ");
Exit (1 );
}

/* Open the file by adding the write method. The content written each time is automatically added to the end of the file */
FD = open ("test.txt", o_rdwr | o_append );
If (FD =-1 ){
Perror ("fail to open ");
Exit (1 );
}

I = 0;
While (I <rest) {/* sets the filling content, and the remaining file content is filled with the character '0 '*/
Buf [I] = '0 ';
I ++;
}

If (write (FD, Buf, rest) =-1) {/* fill file */
Perror ("fail to write ");
Exit (1 );
}

Close (FD);/* close the file */

Return 0;
}

 

To truncate an opened file, use the following function:

 

# Include <unistd. h>

Int ftruncate (INT filedes, off_t set );

 

 

 

7. Clear an object

Truncates the file to 0.

 

 

8. file read/write operations

Read operation:

# Include <unistd. h>

Ssize_t read (int fd, void * Buf, size_t count );
Function Description: Read () transfers the file referred to by the FD parameter to the Buf pointer within count bytes.
. If the Count parameter is 0, read () does not work and 0 is returned. The returned value is real.
Number of bytes read. If 0 is returned, it indicates that the object has reached the end of the file or cannot be read.
Data, in addition, the file read and write location will move with the read bytes.
Additional instructions: If read () succeeds, the actual number of bytes read will be returned.
Count. If the number of returned bytes is less than the number of required bytes, it is possible
Read to the end of the file, read from the pipeline (PIPE) or terminal, or read () is signal
The read operation is interrupted. If an error occurs,-1 is returned. The error code is stored in errno, and the file read/write location is unpredictable.
Error Code eintr this call is interrupted by the signal.
Eagain: When I/O cannot be blocked (o_nonblock), if no data can be read
Returns this value.
The ebadf parameter FD is a non-valid file description word, or the file is closed.


The READ function does not add the '/0' terminator to the end of the read content. If you need it again, add it yourself.

 

# Deprecision max 100

Char Buf [Max];

Int nbytes;

Nbytes = read (FD, Buf, MAX-1 );

Buf [nbytes] = '/0 ';

 

Write operation:

# Include <unistd. h>
Define the function ssize_t write (int fd, const void * Buf, size_t count );
Function Description: Write () will write the memory referred to by the parameter Buf into the count byte to the text referred to by the parameter FD
. Of course, the file read/write location will also move.
If the return value is successfully written (), the actual number of bytes written will be returned. Returns if an error occurs.
Back to-1. The error code is stored in errno.
Error Code eintr this call is interrupted by the signal.
Eagain: When I/O cannot be blocked (o_nonblock), if no data can be read
Returns this value.
The EADF parameter FD is a non-valid file description word, or the file is closed.

 

The following example implements the CP operation

// My_cp.c

# Include <stdio. h>
# Include <stdlib. h>
# Include <fcntl. h>
# Include <unistd. h>
# Define Max 64

/* Simple implementation of the Linux CP command. Command Format: CP des SRC
* 0 is returned for success,-1 is returned for failure, and the cause of failure is saved in errno.
* Argv [1]: target file name des (this example uses absolute path)
* Argv [2]: source file name SRC (this example uses the absolute path)
*/
Int main (INT argc, char * argv [])
{
Char Buf [Max];
Int In, out;/* input and output files */
Int N;

If (argc! = 3)
Exit (1 );

If (in = open (argv [2], o_rdonly) =-1) {/* source file, "read-only" Open */
Perror ("fail to open ");
Exit (1 );
}

/* Target file. If the file does not exist, it is created. If the file exists, it is overwritten and only written to open */
If (out = open (argv [1], o_wronly | o_trunc | o_creat) =-1 ){
Perror ("fail to open ");
Exit (1 );
}

While (n = read (in, Buf, max)> 0)/* Read File */
If (write (Out, Buf, n )! = N) {/* the actual number of written bytes is not equal to N. Write Error */
Perror ("fail to write ");
Exit (1 );
}

If (n <0) {/* An error occurred while reading */
Perror ("fail to read ");
Exit (1 );
}

Printf ("copy done/N");/* output prompt information */

Close (in);/* close two files */
Close (out );

Return 0;
}

 

 

9. file synchronization

 

Forces the change in the buffer zone to be written back to the disk.

 

# Include <unistd. h>

Int fsync (INT filedes );

Int fdatasync (INT filedes );

Void sync (void );

 

Sync only puts the modified disk block into the system queue and returns the result, not waiting for the actual data to be written to the external store. Therefore, this function can only accelerate file synchronization, but cannot guarantee real file synchronization.

The fsync function ensures that the file is actually written, because the function will be blocked until it is written to the external store.

 

# Include <stdio. h>
# Include <stdlib. h>
# Include <fcntl. h>
# Include <unistd. h>

Int main (void)
{
Int FD;
Int I;

FD = open ("test.txt", o_rdwr);/* open a file in writable mode */
If (FD =-1 ){
Perror ("fail to open ");
Exit (1 );
}

I = 0;
While (I <3 ){
Sleep (5);/* sleep for five seconds */

Printf ("Hello/N ");
If (write (FD, "Hello/N", 6) =-1) {/* output a line of string to the file as the prompt message */
Perror ("fail to write ");
Exit (1 );
}

If (fsync (FD) =-1) {/* synchronize the file immediately after the output information to ensure that the output information is instantly written back to the disk */
Perror ("fail to fsync ");
Exit (1 );
}

I ++;
}

Close (FD);/* close the file */

Return 0;
}

 

 

 

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.