Linux C Advanced Programming--system invocation of file operations

Source: Internet
Author: User
Tags function prototype readable

Linux C Advanced Programming file Operation system Calls


Tenet: Technical learning is limited, sharing the spirit of unlimited!


Library functions are functions that perform certain functions, usually published by a standard organization, and form certain standards. Functions written using library functions can generally be applied to different platforms without any modification, which is very portable.

System call functions are directly related to the operating system, and the system calls used by different operating systems may not be the same, so if the two operating systems differ greatly, the portability of the system call functions is not high. For example, applications that Windows uses for system calls cannot be run directly under Linux.

The use of system calls is due to the limited system resources and the convenience of kernel management, the system calls the application development in the upper layer and the underlying hardware implementation, the upper application does not need to pay attention to the implementation of the underlying hardware. Linux system calls are implemented using soft interrupts, and the state of the program is switched from the user to the kernel when the system call is used. The library function implementation eventually calls the system call function, but it encapsulates the system invoke operation, which increases the portability of the code.

1 , Open () function

--for opening or creating a file

(1) Function prototype:

#include <sys/types.h> #include <sys/stat.h> #include <fcntl.h>int open (constchar* pathname, int Flags, ...)

(2) Parameters

Pathname: The file name to create or open

Flags: Specify open mode, flags, and other information for the file

One must be specified: o_rdonly--read-only o_wronly--write-only o_rdwr--read/write

Optional flag (bitwise OR): o_append--append

o_trunc--If the file exists, read-write mode on or write-only open, the file length is 0

o_creat--If the file does not exist, the file is created, at which point the open requires a third parameter that specifies the access permission for the file (Umask can see the mask)

o_excl--If the O_CREAT flag is specified, and the file already exists, an error occurs, which can be used for the existence of the file

O_nonblock for device files, open in O_nonblock mode can do non-blocking I/O

(3) Return value

Integer type--when successful, returns a file descriptor; 1 when an error occurs

(4) File descriptor

(File descriptor-the index of an open file-finds an open file by index)

The file descriptor is a non-negative integer

The file descriptor 0,1,2 represents standard input, standard output, standard error output, and is already open when the process is created . The file descriptor returned by open must be the smallest descriptor that the process has not used

(5) Error handling

Errno.h header file, the errno is defined, and errno describes the specific cause of the error when the API call is faulted

Errno can be easily understood as integral data

Error message converted to a readable string

#include <string.h>

char* strerror (int errno);

The PERROR function outputs an error message based on the current errno (void Perror (constchar* msg))

#include <stdio.h> #include <stdlib.h> #include <sys/types.h> #include <sys/stat.h> #include <fcntl.h>int Main (int argc, char *argv[]) {  int fd;  if (ARGC < 2)  {    puts ("Please input the Open filepathname!\n");    Exit (1);  }  If o_creat in the flag parameter indicates that the file does not exist, the system creates the file, and the permission of the document is          determined by the third parameter, which is 0755  //If there is no o_creat parameter in the Flah parameter, the third parameter does not work. At this point, If the file you want to open          does not exist, an error will be found.  So Fd=open (ARGV[1],O_RDWR), just open the specified file  if (fd = open (argv[1], o_creat | O_rdwr, 0755)) < 0)  {    perror ("Open filefailure!\n");    Exit (1);  }  else  {    printf ("Open file%d  success!\n", FD);  }  Close (FD);  return 0;} <span style= "font-family:arial, Helvetica, Sans-serif; Background-color:rgb (255, 255, 255); " > </span>

2 , creat () function

--Used to create a new file

(1) Function prototypes

int creat (const char *pathname,mode_t mode)

(2) Parameters

Pathname: The name of the file to be created (including path information)

Mode: The second argument with open discusses the file access bit when parsing:

s_irusr--readable s_iwusr--writable s_ixusr--executable s_irwxu--readable, write, execute

In addition to using the macros above, you can also use numbers to represent permissions for a file:

Readable--4 writable--2 executable--1 without any permissions--0

(3) Return value

Successful return write-only open file descriptor, error 1

(4) creat function Disadvantage: It opens the created file in write-only mode. To create a temporary file, write the file first, and then read the file again, you must first call Creat,close, and then open. Simple method:

Open (pathname,o_rdwr| O_creat | O_trunc,mode);

#include <stdio.h> #include <stdlib.h> #include <sys/types.h> #include <sys/stat.h> #include  What are the properties of <fcntl.h>void Create_file (char *filename) {/  * files created? */  if (creat (filename, 0755) < 0)  {    printf ("Create File%sfailure!\n", filename);    Exit (exit_failure);  }  else  {    printf ("Create file%s success!\n", filename);}  } int main (int argc, char *argv[]) {  int i;  if (ARGC < 2)  {    perror ("You haven ' t input thefilename,please try again!\n");    Exit (exit_failure);  }  for (i = 1; i < argc; i++)  {    create_file (argv[i]);  }  return 0;}

3 , Lseek function ( similar to fseek )

--Used to modify the current file offset

(The role of the current file offset: Specifies where to start reading and writing from the file)

-Typically, when a read-write operation ends, the file offset increases the number of bytes read and written

--When a file is opened, the offset is set to 0 unless the O_APPEND flag is specified

(1) Function prototypes

#include <sys/types.h> #include <unistd.h>off_t lseek (int filedes, off_t offset, int whence)

(2) Parameters

The first parameter filedes:open/creat the file descriptor returned by the function

The second parameter, offset:

Relative offset: You need to combine whence to calculate a true offset

Type off_t: Typically 32 is the data type

The third parameter whence: This parameter is a value of three constants

Seek_set: The current file offset is--offset bytes from the beginning of the file

Seek_cur: Current file offset + offset (can be positive negative)

Seek_end: Current file length + offset (can be positive negative)

(3) return value:

Successful return of new file offset, failed return-1

(4) Gets the current offset:

Off_tcurrent_position;

current_position= Lseek (fd,0,seek_cur);

The Lseek operation does not cause any I/O operations, just modifies the records in the kernel (does not cause disk access operations)

(5) Empty file

--The current file offset may be greater than the length of the file after you modify the file offset using Lseek

-In this case, the next write to the file will be extended to the file

-This creates a void in the file. Read the empty area and return 0

4 , Read function

--Used to read data from a file

(1) Function prototypes

#include <unistd.h>ssize_t read (int fd, void *buff, size_t nbytes)

(2) Parameters

First parameter fd: File descriptor

Second parameter buff: point to buffer for storing data read from a file

The third parameter nbytes:unsigned int; The number of bytes to be read from the file

--the size of the buffer >= nbytes

(3) Return value

Return value type: ssize_t, which is int

Error return-1 success: Returns the number of bytes actually read from the file, and returns 0 when the file is read to the end

(4) In many cases, read actually reads the number of bytes is less than the number of bytes required to read out

--Read the normal file and reach the end of the file before reading the required number of bytes

--when reading from an end device, it is usually read one line at a time

--When reading from the network, the buffer mechanism in the network may cause the Read function to return a value less than the number of bytes required to read

--some record-oriented devices, such as disks, return up to one record at a time

#include <sys/types.h> #include <sys/stat.h> #include <fcntl.h> #include <stdio.h> #define LENGTH 100int Main (void) {int fd, Len; char str[length];  /* Create and Open file */fd = open ("Hello.txt", O_creat | O_rdwr, S_IRUSR | S_IWUSR);  if (FD)  {/    * write Hello, software Weekly String */write (FD, "Hello,software Weekly", strlen ("Hello, software weekl  Y ")); Close (FD);  } FD = open ("Hello.txt", O_RDWR); Len = Read (fd, str, LENGTH);/* Reads the contents of the file */str[len] = ' + '; printf ("%s\n", str); Close (FD);  return 0;} <span style= "font-family:arial, Helvetica, Sans-serif; Background-color:rgb (255, 255, 255); " > </span>  

5 , Write function

--Used to write data to a file

(1) Function prototypes

#include <unistd.h>

ssize_t write (int fd,const void*buff,size_t nbytes)

(2) Parameters

First parameter fd: File descriptor

Second parameter buff: points to the buffer, storing the data that needs to be written to the file

Third parameter nbytes: the number of bytes to write to a file

(3) Return value

Return value type: ssize_t, which is int

Error returned-1, the number of bytes actually written to the file was successfully returned

(4) Reason for write error

--Disk full

--No access rights

--Exceeds the file length limit for a given process

6 , Close function

--Used to close a file that has been opened

(1) Function prototypes

int close (int filedes)

(2) Return value

Successfully returned 0, error returned-1

(3) Parameters

Filedes: File descriptor

(4) When the close function closes a file, all record locks that the process adds to the file are freed

The kernel modifies the structure of the process Open File table, file object, index node table entry, and releases related resources.

When the process exits, all currently open file descriptors are closed

7 , IOCTL function

--Used to send control and configuration commands to the device (these data cannot be read and written by Read/write)

(1) Function prototypes

#include <sys/ioctl.h>int ioctl (int d, int request, ...)

(2) Parameters

First parameter D: file descriptor for a device

The second parameter, request: is the IOCTL command, and the variable parameter depends on the request, usually a pointer to a variable or struct.

(3) Return value

If the error returns 1, the other value is returned successfully, depending on the request

IOCTL (stdout_fileno,tiocgwinsz,&size)--To obtain the window size of the end device

manioctl_list--can look at the various parameters of require

8 , mmap function

--You can map a portion of a disk file directly to memory, so that the location of the file directly has a corresponding memory address, read and write to the file can be done directly with pointers without the need for read/write function

(1) Function prototypes

#include <sys/mman.h>

void* mmap (void *addr,size_t len,int prot,int flag,int filedes,off_t off)

(2) Parameters

The addr:null--kernel will itself select the appropriate address in the process address space to establish the mapping

Len: The length of the part of the file that needs to be mapped

Off: Starting from where the file is mapped, must be an integer multiple of the page size (32-bit--4k)

Filedes: File descriptor for this file

Prot

This section of the prot_exec--map is executable, such as a mapped shared library

This section of the prot_read--map is readable

This section of the prot_write--map can be written

This section of the prot_none--map is not accessible

Flag

map_shared--the mapping of multiple processes to the same file is shared, one process modifies the mapped memory, and another process sees this change.

map_private--the mapping of multiple processes to the same file is not shared, one process modifies the mapped memory, and the other process does not see the change, nor does it actually write to the file.

(3) Return value

Success returns the first address of the map, and the error returns the constant map_failed.

9 , Access function

--Determine if a file can perform some sort of operation

(1) Function prototypes

int access (const char *pathname,int mode)

(2) Parameters

Pathname: File name

Mode: Determine access rights: R_OK: File readable w_ok: File writable

X_OK: File executable f_ok: File exists

(3) Return value

When successful, returns 0, or 1 if a condition is not met

Ten DUP function

--Copy file descriptor

(1) Function prototypes

#include <unistd.h>int dup (int oldfd);

(2) Parameters

OLDFD: File descriptor to be copied

(3) Return value

A new file descriptor was successfully returned; 1 failed

dup2 function

--Copy file descriptor

(1) Function prototypes

#include <unistd.h>int dup2 (int oldfd, int newfd);

(2) Parameters

OLDFD: File descriptor to be copied

NEWFD: New File descriptor

(3) Return value

A new file descriptor was successfully returned; 1 failed

Small project: The function of using the system call function to copy files:/************************************************************************* > File Name: copy.c > Author:libang > Mail: [email protected] > Created time:2014 year July 16 Wednesday 00:15 12 sec. ******* /#include <stdio.h> #include <string.h > #include <unistd.h> #include <sys/stat.h> #include <sys/types.h> #include <fcntl.h>#   Include<stdlib.h>int copy_file (intsrc_fd, int dest_fd); int main (INTARGC, Char *argv[])//Note first building the main frame {if (ARGC < 3)    {printf ("inputerror!\n");  Exit (1);  } int src_fd, DEST_FD;  SRC_FD = open (argv[1], o_rdonly); DEST_FD = open (argv[2], o_wronly | O_creat |  O_trunc, 0666);    if (src_fd < 0 | dest_fd < 0) {printf ("file openfail!\n");  Exit (0);  } copy_file (SRC_FD, DEST_FD);  printf ("success!\n");  Close (SRC_FD);  Close (DEST_FD); return 0;}  int Copy_file (INTSRC, int dest) {char buf[128];  int R_ret, W_ret; Char *tmp;  memset (buf,0,128);  printf ("success!\n");    while ((R_ret = Read (src, buf)) > 0)//Classic copy algorithm {tmp = BUF;      while (R_ret) {W_ret = write (dest, TMP, R_ret);      R_ret = R_ret-w_ret;      printf ("%d\n", R_ret);    TMP + = W_ret;  }//memset (buf,0,128);  } printf ("success!\n"); return 0;}

Linux C Advanced Programming--system invocation of file operations

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.