3) getting started with Linux programming-File Operations

Source: Internet
Author: User

3) getting started with Linux programming-File Operations
File Operations in Linux
Preface:
In this section, we will discuss various functions for file operations in Linux.
File Creation and read/write
File Attributes
Directory file operations
MPs queue File
------------------------------------------------------------------------
1. File Creation and read/write
I suppose you already know all the functions for standard file operations (fopen, fread, fwrite, etc.).
If you do not know, do not worry. The system-level file operations we discuss are actually standard-level file operations.
Service.
When we need to open a file for read/write operations, we can use the system to call the function open.
Then, we call another close function to close the function.
# Include <fcntl. h>
# Include <unistd. h>
# Include <sys/types. h>
# Include <sys/STAT. h>

Int open (const char * pathname, int flags );
Int open (const char * pathname, int flags, mode_t mode );
Int close (int fd );
The open function has two forms. pathname is the name of the file we want to open (including the path name, which is considered in
Under the current path). flags can go to a value below or a combination of several values.
O_rdonly: open the file in read-only mode.
O_wronly: open the file in write-only mode.
O_rdwr: open a file in read/write mode.
O_append: open the file in append mode.
O_creat: Creates a file.
O_exec: If o_creat is used and the file already exists, an error occurs.
O_noblock: open a file in non-blocking mode.
O_trunc: if the file already exists, delete the file content.
Only one of the first three logos can be used. If the o_create flag is used
The Mode flag must be specified to indicate the object access permission. mode can be a combination of the following conditions.
-----------------------------------------------------------------
S_irusr users can read s_iwusr users can write
S_ixusr user can execute s_irwxu user can read and write execution
-----------------------------------------------------------------
S_irgrp group can read s_iwgrp group can write
S_ixgrp group can run s_irwxg group can read and write
-----------------------------------------------------------------
S_iroth others can read s_iwoth others can write
S_ixoth others can execute s_irwxo others can read and write
-----------------------------------------------------------------
S_isuid: Set the user execution ID s_isgid: Set the execution ID of the Group
-----------------------------------------------------------------
We can also use numbers to represent the symbols of each bit. Linux uses a total of five numbers to represent various permissions of the file.
00000. the first digit indicates setting the user ID. The second digit indicates setting the group ID, the third digit indicates the user's own permission, and the fourth digit indicates setting the group ID.
Bit indicates the permissions of the group, and the last bit indicates the permissions of others.
Each number can be 1 (Execution permission), 2 (write permission), 4 (read permission), 0 (nothing), or the sum of these values.
..
For example, if you want to create a user read/write execution, the group does not have the permission. If you want to set the user ID
The mode we can use is -- 1 (Set User ID) 0 (group not set) 7 (1 + 2 + 4) 0 (no permission, use the default)
5 (1 + 4) is 10705:
Open ("Temp", o_creat, 10705 );
If the file is successfully opened, open will return a file descriptor. We can perform all subsequent operations on the file.
The file descriptor is operated.
After the operation is complete, we need to close the file. We only need to call close, and FD is the one we want to close.
File descriptor.
After the file is opened, we need to read and write the file. We can call the Read and Write Functions for file
Read/write.
# Include <unistd. h>
Ssize_t read (int fd, void * buffer, size_t count );
Ssize_t write (int fd, const void * buffer, size_t count );
FD is the file descriptor for read/write operations. buffer is the file content to be written or read.
Memory Address. Count is the number of bytes to read and write.
For normal File Read, read the Count byte from the specified file (FD) to the buffer zone (remember that we must
Must provide a buffer that is large enough) and return count.
If the read reads the end Of the file or is interrupted by a signal, the returned value is smaller than count.
If no data is returned due to disconnection, read returns-1 and errno is set to eintr. When the program reads the file
At the end of the statement, read returns 0.
Write writes the Count byte from the buffer to the file FD. The actual number of bytes written is returned when the operation is successful.
Next we will learn an instance which is used to copy files.
# Include <unistd. h>
# Include <fcntl. h>
# Include <stdio. h>
# Include <sys/types. h>
# Include <sys/STAT. h>
# Include <errno. h>
# Include <string. h>
# Define buffer_size 1024
Int main (INT argc, char ** argv)
{
Int from_fd, to_fd;
Int bytes_read, bytes_write;
Char buffer [buffer_size];
Char * PTR;
If (argc! = 3)
{
Fprintf (stderr, "Usage: % s fromfile tofile/n/a", argv [0]);
Exit (1 );
}
/* Open the source file */
If (from_fd = open (argv [1], o_rdonly) =-1)
{
Fprintf (stderr, "Open % s error: % s/n", argv [1], strerror (errno ));
Exit (1 );
}
/* Create the target file */
If (to_fd = open (argv [2], o_wronly | o_creat, s_irusr | s_iwusr) =-1)
{
Fprintf (stderr, "Open % s error: % s/n", argv [2], strerror (errno ));
Exit (1 );
}
/* The following code is a classic copy file code */
While (bytes_read = read (from_fd, buffer, buffer_size ))
{
/* A fatal error occurred */
If (bytes_read =-1) & (errno! = Eintr) break;
Else if (bytes_read> 0)
{
PTR = buffer;
While (bytes_write = write (to_fd, PTR, bytes_read ))
{
/* A fatal error occurred */
If (bytes_write =-1) & (errno! = Eintr) break;
/* All read bytes have been written */
Else if (bytes_write = bytes_read) break;
/* Write only a part and continue writing */
Else if (bytes_write> 0)
{
PTR + = bytes_write;
Bytes_read-= bytes_write;
}
}
/* Fatal error during write */
If (bytes_write =-1) break;
}
}
Close (from_fd );
Close (to_fd );
Exit (0 );
}
2. File Attributes
The file has various attributes. In addition to the file permissions we know above, the file still has the creation time.
, Size, and other attributes.
Sometimes we need to determine whether a file can perform certain operations (read, write, and so on). At this time, we can use acce.
SS function.
# Include <unistd. h>

Int access (const char * pathname, int mode );
Pathname: indicates the file name and mode is the attribute to be judged. You can take the following values or their combinations.
The r_ OK file can be read, The w_ OK file can be written, the x_ OK file can be executed, and the f_ OK file exists. when the test is successful
The function returns 0. Otherwise,-1 is returned if one of the conditions does not match.
If we want to obtain other attributes of the file, we can use the stat or fstat function.
# Include <sys/STAT. h>
# Include <unistd. h>
Int Stat (const char * file_name, struct stat * BUF );
Int fstat (INT filedes, struct stat * BUF );
Struct stat {
Dev_t st_dev;/* Device */
Ino_t st_ino;/* node */
Mode_t st_mode;/* mode */
Nlink_t st_nlink;/* hard connection */
Uid_t st_uid;/* User ID */
Gid_t st_gid;/* Group ID */
Dev_t st_rdev;/* device type */
Off_t st_off;/* Number of file bytes */
Unsigned long st_blksize;/* block size */
Unsigned long st_blocks;/* number of blocks */
Time_t st_atime;/* last access time */
Time_t st_mtime;/* last modification time */
Time_t st_ctime;/* last change time (attribute )*/
};
Stat is used to determine files that are not opened, while fstat is used to determine files that are opened. The most commonly used attribute is st _
Mode. Through the attribute, we can determine whether the given file is a common file or a directory, connection, and so on.
Use the following macros to determine.
S_islnk (st_mode): whether it is a connection. s_isreg is a regular file. s_isdir is a project
Check whether s_ischr is a character device. Whether s_isblk is a block device s_isfifo is a FIFO file
. S_issock is a socket file. We will explain how to use these macros below.
3. Directory file operations
When we write a program, we sometimes need to get our current working path. Library C functions provide get
CWD to solve this problem.
# Include <unistd. h>

Char * getcwd (char * buffer, size_t size );
We provide a buffer of the size. getcwd will test our current path to the buffer. If the buffer
The function returns-1 and an error number.
Linux provides a large number of directory operation functions. We will learn a few simple and common functions.
# Include <dirent. h>
# Include <unistd. h>
# Include <fcntl. h>
# Include <sys/types. h>
# Include <sys/STAT. h>
Int mkdir (const char * path, mode_t mode );
Dir * opendir (const char * path );
Struct dirent * readdir (dir * DIR );
Void rewinddir (dir * DIR );
Off_t telldir (dir * DIR );
Void seekdir (dir * Dir, off_t off );
Int closedir (dir * DIR );
Struct dirent {
Long d_ino;
Off_t d_off;
Unsigned short d_reclen;
Char d_name [name_max + 1];/* file name */
Mkdir is easy to create a directory. opendir opens a directory to prepare for future read. readdir read 1
Directory. rewinddir is used to re-read the directory. It is the same as the rewind function we learned. closedir is disabled.
A directory. telldir and seekdir are similar to the ftee and fseek functions.
Below we develop a small program, which has a parameter. If this parameter is a file name, we output
File Size and last modification time. If it is a directory, We output the size and
Modification time.
# Include <unistd. h>
# Include <stdio. h>
# Include <errno. h>
# Include <sys/types. h>
# Include <sys/STAT. h>
# Include <dirent. h>
# Include <time. h>
Static int get_file_size_time (const char * filename)
{
Struct stat statbuf;
If (STAT (filename, & statbuf) =-1)
{
Printf ("Get stat on % s error: % s/n ",
Filename, strerror (errno ));
Return (-1 );
}
If (s_isdir (statbuf. st_mode) Return (1 );
If (s_isreg (statbuf. st_mode ))
Printf ("% s size: % LD Bytes/tmodified at % s ",
Filename, statbuf. st_size, ctime (& statbuf. st_mtime ));

Return (0 );
}
Int main (INT argc, char ** argv)
{
Dir * dirp;
Struct dirent * direntp;
Int stats;
If (argc! = 2)
{
Printf ("Usage: % s filename/n/a", argv [0]);
Exit (1 );
}
If (Stats = get_file_size_time (argv [1]) = 0) | (Stats =-1) Exit (1 );
If (dirp = opendir (argv [1]) = NULL)
{
Printf ("Open Directory % s error: % s/n ",
Argv [1], strerror (errno ));
Exit (1 );
}
While (direntp = readdir (dirp ))! = NULL)
If (get_file_size_time (direntp-<d_name) =-1) break;
Closedir (dirp );
Exit (1 );
}
4. MPs queue File
Linux provides many filtering and redirection programs, such as more cat
And so on. The redirection operators such as <>|< are also provided.
The system calls pipe to create an MPS queue.
# Include <unistd. h>

Int pipe (INT Fildes [2]);
Pipe call can create an MTS Queue (Communication buffer). When the call is successful, we can access the file descriptor fild.
Es [0], Fildes [1]. Where Fildes [0] is the file descriptor for reading, And Fildes [1] is the file description used for writing.
Operator.
In actual use, we create a sub-process, write a process, and read it by a process.
For more information about Process Communication, see Process Communication.
# Include <stdio. h>
# Include <stdlib. h>
# Include <unistd. h>
# Include <string. h>
# Include <errno. h>
# Include <sys/types. h>
# Include <sys/Wait. H>
# Define buffer 255.
Int main (INT argc, char ** argv)
{
Char buffer [buffer + 1];
Int FD [2];
If (argc! = 2)
{
Fprintf (stderr, "Usage: % s string/n/a", argv [0]);
Exit (1 );
}
If (pipe (FD )! = 0)
{
Fprintf (stderr, "pipe error: % s/n/a", strerror (errno ));
Exit (1 );
}
If (Fork () = 0)
{
Close (FD [0]);
Printf ("child [% d] Write to pipe/n/a", getpid ());
Snprintf (buffer, buffer, "% s", argv [1]);
Write (FD [1], buffer, strlen (buffer ));
Printf ("child [% d] Quit/n/a", getpid ());
Exit (0 );
}
Else
{
Close (FD [1]);
Printf ("parent [% d] read from pipe/n/a", getpid ());
Memset (buffer, '', buffer + 1 );
Read (FD [0], buffer, buffer );
Printf ("parent [% d] Read: % s/n", getpid (), buffer );
Exit (1 );
}
}
To implement the redirection operation, we need to call another function dup2.
# Include <unistd. h>

Int dup2 (INT oldfd, int newfd );
Dup2 uses the oldfd file descriptor to replace the newfd file descriptor, and closes the newfd file descriptor. That is
,
All operations directed to newfd are forwarded to oldfd. The following is an example. This example redirects the standard output.
To a file.
# Include <unistd. h>
# Include <stdio. h>
# Include <errno. h>
# Include <fcntl. h>
# Include <string. h>
# Include <sys/types. h>
# Include <sys/STAT. h>
# Define buffer_size 1024
Int main (INT argc, char ** argv)
{
Int FD;
Char buffer [buffer_size];
If (argc! = 2)
{
Fprintf (stderr, "Usage: % s outfilename/n/a", argv [0]);
Exit (1 );
}
If (FD = open (argv [1], o_wronly | o_creat | o_trunc, s_irusr | s_iwusr) =-1)
{
Fprintf (stderr, "Open % s error: % s/n/a", argv [1], strerror (errno ));
Exit (1 );
}
If (dup2 (FD, stdout_fileno) =-1)
{
Fprintf (stderr, "Redirect standard out error: % s/n/a", strerror (errno ));
Exit (1 );
}
Fprintf (stderr, "now, please input string ");
Fprintf (stderr, "(to quit use Ctrl + d)/n ");
While (1)
{
Fgets (buffer, buffer_size, stdin );
If (feof (stdin) break;
Write (stdout_fileno, buffer, strlen (buffer ));
}
Exit (0 );
}
Now, we will discuss the document chapter here for the time being. after learning the file operation, we can write
Some useful programs. We can compile a common file operations such as Dir, mkdir, CP, and MV.
Command.
Do you want to give me a try?

 

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.