System File Operation Development

Source: Internet
Author: User
Tags flock touch command

1. System file read/write

Task Description:

Write the program, read the Linux system file "/etc/passwd" content, and output to the screen. In the program directory, create a new file passwd and copy the contents of the "/etc/passwd" System file to the new passwd

MAIN.C:

#include <stdio.h>#include<unistd.h>#include<stdlib.h>#include<sys/types.h>#include<sys/stat.h>#include<fcntl.h>#defineN 1000intMainvoid){    intFp1,fp2,num; Char*file1,*file2; CharBuf[n]; File1="/etc/passwd"; File2="passwd"; if((Fp1=open (file1,o_rdonly)) ==-1) {printf ("can ' t open%s\n", file1); return 1; }    if((Fp2=open (file2,o_creat| o_wronly)) ==-1) {printf ("can ' t create%s\n", file2); return-1; }     while(num = read (fp1,buf,n)) >0) {printf ("%s\n", BUF); if(Write (fp2,buf,num) = =-1) {printf ("can ' t write to%s\n", file2); return-1;    }} close (FP1); close (FP2); return 0; }

2, File content statistics operation

Task Description:

    • Given system file Filesystem.manifest (dpkg-query-w--showformat= ' ${package} ${version}\n ' >filesystem.manifest)
    • The current file in each line format is "package name version number", the output of each line is required to format "package name" (remove the version number related information) to the file Filesystem.manifest.name
    • On the basis of the first step, further remove the newline symbol, so that the output of the entire file is a line (different package name is separated by a space), the format is "Package 1 package 2 Package 3 ...", Output to file Filesystem.manifest.name.oneline
    • Currently, the format of each line is "package name version number", found in the file package name has "Ubuntu" package, and directly output its number (can not be manually searched, need to directly output its number)

Related knowledge:

The ①cut command extracts text columns from a text file or text stream.
Command usage:
Cut-b list [-n] [file ...]
CUT-C list [File ...]
Cut-f list [-D delim][-s][file ...]
The-B,-C, and-F above represent bytes, characters, fields (that is, Byte, character, field), respectively;
List represents the-B,-C,-f operation range,-n often denotes specific numbers;
File represents the natural name of the text file to manipulate;
Delim (fully written in English: delimiter) represents the delimiter, which is TAB by default;
-S means not including those lines that do not contain delimiters (this helps to remove comments and headings)
In the above three ways, the bytes are extracted from the specified range (-B), or the character (-c), or the field (-f).

②Xargs is a common command for UNIX and UNIX-like operating systems. It does this by converting the argument list to small pieces to pass to other commands to avoid the problem of too long a parameter list.

For example, the following command:
RM ' Find/path-type f ' if there are too many files in the path directory, the error cannot be performed because the parameter list is too long. But after switching to Xargs, the problem is resolved.
Find/path-type f-print0 | xargs-0 RM
In this example, Xargs splits the long list of files produced by find into multiple substrings, and then calls RM for each substring. This is much more efficient than using the Find command as follows.
Find/path-type f-exec rm ' {} ' \; The
above command calls the RM command on each file. Of course, using the new version of "Find" can also get the same effect as the "Xargs"
Command:
Find/path-type f-exec rm ' {} ' +
Xargs is generally equivalent to the anti-quotes in most Unix shells, but more flexible and easy to and can correctly handle special characters such as spaces in the input.
is useful for commands that often produce large amounts of output, such as find, locate, and grep.

 #!/bin/bashdpkg -query-w--showformat= ${package} ${version}\n   " >< Span style= "color: #000000;" >filesystem.manifestcat filesystem.manifest  |cut-d  "  ' -f   '  indicates a space character-f 1 means output first column # Xargs means that the argument list is converted to small pieces to be passed to other commands to avoid a problem with the argument list being too long  

3. File Descriptor Acquisition

Task Description:

    • Print input device, output device, standard error output device file descriptor
    • Open an existing file A to print its file descriptor
    • Do not close file A, define a new file descriptor reopen A, print its file descriptor
    • Close file A, define new file descriptor reopen A, print file descriptor

Related knowledge:

Any open file will be assigned a file descriptor that uniquely identifies the open file as an integer greater than or equal to 0. After the system starts, the file streams that are opened by default are standard input devices (STDIN), standard output devices (STDOUT), and standard error output devices (STDERR), with file descriptors of 0, 1, and 2, respectively. File descriptor allocations for later open files are incremented in turn. Use the Fileno () function to return a file descriptor for a stream.

MAIN.C:

#include <stdio.h>int  main () {    *fp1,*fp2,*fp3,*fp4;     int FD;    FD=fileno (stdin);
printf ("stdin is:%d\n", FD); FD=fileno (stdout);
printf ("stdout is:%d\n", FD); FD=fileno (stderr);
printf ("stderr is:%d\n", FD);
printf ("Open file and open again before it closed\n");
FP1=fopen ("test.c", "R");
FD=Fileno (FP1);
printf ("Main.c is%d\n", FD);
FP2=fopen ("test.c","R");
FD=Fileno (FP2);
printf ("Main.c is%d\n", FD);
fclose (FP1); fclose (FP2);
printf ("open File and open again after it closed\n"); FP3=fopen ("test.c","R"); FD=Fileno (FP3); printf ("Main.c is%d\n", FD);    Fclose (FP3); FP4=fopen ("test.c","R"); FD=Fileno (FP4); printf ("Main.c is%d\n", FD); return 0;}

4. test file read and Write permission

Task Description:

    • Detects the file's current read and write permissions, prints readable information if the file has Read permissions, and prints writable information if write permission otherwise returns an error message
    • Using the FCNTL function to implement

Related knowledge:

Fcntl function Description: Manipulate the characteristics of a file according to the file description Word.
File control functions: Fcntl
Function Prototypes:
#include <fcntl.h>;
int fcntl (int fd, int cmd);
int fcntl (int fd, int cmd, long arg);
int fcntl (int fd, int cmd, struct flock *lock);
Description: Fcntl () provides control over (file) descriptors. The parameter FD is a descriptor of the parameter CMD operation (as described below). For a value of CMD, Fcntl can accept the third argument, int arg.
There are 5 functions of the FCNTL function:
1. Copy an existing descriptor (CMD=F_DUPFD).
2. Get/Set the file descriptor tag (CMD=F_GETFD or F_SETFD).
3. Get/Set the file status tag (CMD=F_GETFL or F_SETFL).
4. Get/Set asynchronous I/O ownership (Cmd=f_getown or F_setown). 5. Get/Set record lock (CMD=F_GETLK,F_SETLK or F_SETLKW).

MAIN.C:

#include <stdio.h>#include<fcntl.h>intMainvoid) {FILE*FP; intVal,acc,a; if((Fp=fopen ("test.c","r+")) ==NULL) {printf ("can ' t open the file\n"); return 1; } A=Fileno (FP); Val=fcntl (A,F_GETFL,0);//Get file Status tagsacc=val&o_accmode;//Masking file status tags that are not about R, W, x    if(acc==o_rdonly) printf ("Read only\n"); if(acc==o_wronly) printf ("Write only\n"); if(acc==o_rdwr) printf ("Read write\n");    Fclose (FP); return 0;}

5. Lock/Unlock Files

Task Description:

    • Using the FCNTL function to lock the file Test_lock two regions, the locking type is the beginning of the file as the starting position of the lock, area 1 is locked for reading, the starting offset is 10, the length is 20, the region 2 is locked for writing, the starting offset is 40, and the length is 10.
    • Outputs "Process locking file", pauses for 10 seconds, closes the file descriptor, and outputs "process closing file" when the process locks the specified zone
    • Using the flock data structure, use the FCNTL function

Related knowledge:

  The file lock technology supported by Linux mainly includes advising on the lock (Advisory lock) and the forced lock (mandatory lock) of both. In addition, there are two variants of forced locks introduced in Linux: Shared mode Force lock (Share-mode mandatory lock) and rental lock (lease).
In Linux, it can use both shared and exclusive locks (also known as read and write locks), regardless of whether the process is using the advise or force lock. Multiple shared locks do not interfere with each other, and multiple processes can share locks on the same file at the same time. However, if a process adds an exclusive lock to the file, the other process does not have permission to share the file with a lock or an exclusive lock until the exclusive lock is freed. So, for the same file, it can have a lot of readers at the same time, but at a certain point, it only has a writer

the F lock function is used to implement lock and unlock operations on files. This function only locks the entire file and cannot lock a region. To lock an area, you need to use the Fcntl () function.

int fcntl (int fd, int cmd, struct flock *lock); The parameter lock pointer is a flock structure pointer, defined as follows:

struct flock{short int l_type;    short int l_whence;    off_t L_start;    off_t L_len;  pid_t L_pid;  }; There are three states of L_type: F_rdlck Creating a lock for reading F_wrlck Creating a lock for write-inF_unlck There are three ways to delete a previously established lock L_whence: Seek_set begins with the start of the file as the starting position of the lock. Seek_cur the starting position at which the current file read and write position is locked seek_end the end of the file as the starting position of the lock.  L_start represents the offset of the relative l_whence position, which together determine the starting position of the locked area. L_len indicates the length of the locked area, if 0 means starting from the starting point (starting at the beginning of the l_whence and L_start) until the maximum possible offset is reached. That is, no matter how much data is added later, it is within the scope of the lock.

  MAIN.C:

#include <stdio.h>#include<fcntl.h>intMainvoid){    intRE,FD; FD=open ("Test_lock", o_rdwr| O_creat,0644); structFlock Z1; Z1.l_type=f_rdlck;//Create a lock for readingZ1.l_whence=seek_set;//start with the beginning of the file as the starting position of the lockz1.l_start=Ten; Z1.l_len= -; printf ("Process%d locking file\n", Getpid ()); if((Re=fcntl (FD,F_SETLK,&AMP;Z1)) ==-1) {printf ("failed to lock Z1"); }    structFlock Z2; Z2.l_type=f_wrlck;//Create a lock for write-inZ2.l_whence=seek_set;//start with the beginning of the file as the starting position of the lockz2.l_start= +; Z2.l_len=Ten; if((Re=fcntl (FD,F_SETLK,&AMP;Z2)) ==-1) {printf ("failed to lock Z2"); } Sleep (Ten); printf ("Process%d closing file\n", Getpid ());    Close (FD); return 0;}

6. Use the chmod () function to modify file permissions

Task Description:

    • Start with the touch command to create a new 3 temporary file: Test1,test2,test3
    • View the most original file permission condition (whether the owner can read and write, all other people readable)
    • Set the Test1 for the owner to read and write, the same group of users can read and write, the other person is readable, test2 for the owner can read and write, the same group of users can read and write executable, the other person readable, test3 for the owner can read and write, the same group of users can write unreadable, other users can write non-readable
    • Using stat data knot, chmod function
    • Output file properties before modifying permissions and after modifying permissions

Related knowledge:

Knowledge of file permissions:

Each file and directory in a Linux system has access permissions, which are used to determine who can access and manipulate files and directories.
Access to a file or directory is divided into read-only, write-only, and executable three types. As an example of a file, a read-only permission means that only the content is allowed to be read, and any changes to it are forbidden. Executable permission means that the file is allowed to be executed as a program. When a file is created, the file owner automatically has read, write, and execute permissions on the file to facilitate the reading and modification of the file. Users can also set access rights to any combination they want, as needed. There are three different types of users who can access files or directories: The file owner, the same group of users, and other users.
The owner is typically the creator of the file. The owner can allow the same group of users access to the file, as well as the access rights of the file to other users on the system. In this case, every user in the system can access the files or directories that the user owns.
Each file or directory has three groups of access rights, each group is represented by three bits, respectively, the read, write, and execute permissions of the file owner, the read, write, and execute permissions of the user belonging to the primary group, and the read, write, and execute permissions of other users in the system. When you use the LS-L command to display the details of a file or directory, the leftmost column is the file's access rights.

MAIN.C:

#include <stdio.h>#include<sys/stat.h>#include<unistd.h>intMainvoid) {chmod ("test01", s_irusr| s_iwusr| s_irgrp| s_iwgrp|S_iroth); chmod ("test02", s_irusr| s_iwusr| s_irgrp| s_iwgrp| s_ixgrp|S_iroth); chmod ("test03", s_irusr| s_iwusr| s_iwgrp|S_iwoth); return 0;}

System File Operation Development

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.