Linux C Programming Practice (2)-File System Programming

Source: Internet
Author: User
Tags types of functions

 

Linux C Programming Practice (2)

-File System Programming

 

1. Linux File System

Linux supports multiple file systems, such as ext, ext2, minix, iso9660, msdos, fat, vfat, and nfs. On the upper layer of these file systems, Linux provides virtual

File Systems (VFS) are used to unify their behaviors. Virtual File systems provide consistent interfaces for communication between different file systems and the kernel. This section describes the relationship between file systems in Linux:

<! -- [If! Vml] --> <! -- [Endif] -->

On the Linux platform, two types of functions can be used for file programming: (1) Linux operating system file API; (2) c language I/O library function. the former depends on Linux calls, and the latter is actually independent from the operating system, because in any operating system, the methods for operating files using C language I/O library functions are the same. This chapter provides examples of the two methods.

.

2. Linux File API

The file operation API of Linux involves creating, opening, reading, writing, and closing files.

Create

Int creat (const char * filename, mode_t mode );

The mode parameter specifies the access permission for the new file. It determines the final permission of the file (mode & umask) together with umask. umask indicates some access permissions that need to be removed during file creation.

Permission. Umask can be changed by calling umask:

Int umask (int newmask );

This call sets umask as newmask and returns the old umask, which only affects read, write, and execution permissions.

Open

Int open (const char * pathname, int flags );

Int open (const char * pathname, int flags, mode_t mode );

The open function has two forms. pathname is the name of the file to be opened (including the path name, which is considered to be under the current path by default). flags can go to the following value or

Value combination:

Flag

Description

 

O_RDONLY

Open a file in read-only mode

 

O_WRONLY

Open a file in write-only mode

 

O_RDWR

Open a file in read/write mode

 

O_APPEND

Open an object in append Mode

 

O_CREAT

Create 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.

 

O_RDONLY, O_WRONLY, and O_RDWR can only use any one of them.

If the O_CREATE flag is used, the int open (const char * pathname, int flags, mode_t mode) function is used. In this case, the mode flag must be specified.

Object Access permission. Mode can be a combination of the following conditions:

Flag

Description

 

S_IRUSR

Users can read

 

S_IWUSR

Users can write

 

S_IXUSR

Users can execute

 

S_IRWXU

Users can read, write, and execute

 

S_IRGRP

Group readable

 

S_IWGRP

Group Writable

 

S_IXGRP

Group executable

 

S_IRWXG

The Group can be read and written for execution.

 

S_IROTH

Others can read

 

S_IWOTH

Others can write

 

S_IXOTH

Others can execute

 

S_IRWXO

Others can read, write, and execute

 

S_ISUID

Set User execution ID

 

S_ISGID

Set the execution ID of the Group

 

In addition to the above macro "or" logic to generate a flag, we can also use numbers to represent the various permissions of the file. in Linux, a total of five numbers are used to represent the permissions of the file.

Set the user ID. The second digit indicates the set group ID. The third digit indicates the user's own permission. The fourth digit indicates the Group permission. the last digit indicates the permissions of others. Each number can be 1

Row permission), 2 (write permission), 4 (read permission), 0 (none), or the sum of these values. For example, to create a readable, writable, and executable user, but the group has no permissions, others can read,

Executable File and set the user ID. Then, we should use 1 (Set User ID), 0 (do not set group ID), 7 (1 + 2 + 4, read, write, and execute), 0 (no permission ),

5 (1 + 4, read and execute) is 10705:

Open ("test", O_CREAT, 10705 );

The preceding statement is equivalent:

Open ("test", O_CREAT, S_IRWXU | S_IROTH | S_IXOTH | S_ISUID );

If the file is successfully opened, the open function returns a file descriptor. All subsequent operations on the file can be performed by operating on the file descriptor.

Read/write

After the file is opened, we can read and write the file. in Linux, the read and write Functions are called by the system:

Int read (int fd, const void * buf, size_t length );

Int write (int fd, const void * buf, size_t length );

The parameter buf is the pointer to the buffer, and the length is the buffer size (in bytes ). The read () function reads length characters from the file specified by the file descriptor fd.

In the buffer to which the buf points, the returned value is the number of bytes actually read. Function write writes the length byte from the buffer to which the buf points to the file indicated by the file descriptor fd.

The return value is the number of bytes actually written.

Open marked with O_CREAT actually implements the file creation function. Therefore, the following function is equivalent to the creat () function:

Int open (pathname, O_CREAT | O_WRONLY | O_TRUNC, mode );

Positioning

For random files, we can read and write at random locations and use the following functions to locate them:

Int lseek (int fd, offset_t offset, int whence );

Lseek () moves the file read/write pointer to the offset byte relative to whence. When the operation is successful, the position of the returned file pointer relative to the file header. The whence parameter can use the following values:

SEEK_SET: Start of relative file

SEEK_CUR: Current Position of the relative file read/write pointer

SEEK_END: relative to the end of the file

The offset value can be a negative value. For example, the following call can move the file pointer 5 bytes forward from the current position:

Lseek (fd,-5, SEEK_CUR );

Because the return value of the lseek function is the position of the file pointer relative to the file header, the following returned values are the file length:

Lseek (fd, 0, SEEK_END );

Close

After the operation is complete, we need to close the file. We only need to call close. fd is the file descriptor we want to close:

Int close (int fd );

Routine: compile a program, create a user-readable file named hello.txt in the current directory, write "Hello, software weekly" in it, and close the file. Open

File, read the content and output it on the screen.

# Include <sys/types. h>

# Include <sys/stat. h>

# Include <fcntl. h>

# Include <stdio. h>

# Define LENGTH 100

Main ()

{

Int fd, len;

Char str [LENGTH];

 

Fd = open ("hello.txt", O_CREAT | O_RDWR, S_IRUSR | S_IWUSR);/* Create and open a file */

If (fd)

{

Write (fd, "Hello, Software Weekly", strlen ("Hello, software weekly");/* write the Hello, software weekly string */

Close (fd );

}

Fd = open ("hello.txt", O_RDWR );

Len = read (fd, str, LENGTH);/* read File Content */

Str [len] = '"0 ';

Printf ("% s" n ", str );

Close (fd );

};

 

Compile, run, and execute

 

3. C language library functions

The file operations of C-library functions are actually independent from the specific operating system platform. These functions are used in DOS, Windows, Linux, and VxWorks:

Create and open

FILE * fopen (const char * path, const char * mode );

Fopen () is used to open the specified file filename. The mode is the open mode. The following table lists the open modes supported in C:

Flag

Description

 

R, rb

Open in read-only mode

 

W, wb

Open in write-only mode. If the file does not exist, create the file. Otherwise, the file is truncated.

 

A, AB

Open in append mode. If the file does not exist, create the file.

 

R +, r + B, rb +

Open in read/write mode

 

W +, w + B, wh +

Open in read/write mode. If the file does not exist, create a new file. Otherwise, the file is truncated.

 

A +, a + B, AB +

Open in read and append mode. If the file does not exist, create a new file.

 

B is used to distinguish between binary files and text files, which are differentiated in DOS and Windows systems, but Linux does not distinguish between binary files and text files.

Read/write

The C-database functions support reading and writing files in a certain format in units of characters and strings. These functions are:

Int fgetc (FILE * stream );

Int fputc (int c, FILE * stream );

Char * fgets (char * s, int n, FILE * stream );

Int fputs (const char * s, FILE * stream );

Int fprintf (FILE * stream, const char * format ,...);

Int fscanf (FILE * stream, const char * format ,...);

Size_t fread (void * ptr, size_t size, size_t n, FILE * stream );

Size_t fwrite (const void * ptr, size_t size, size_t n, FILE * stream );

Fread () reads n fields from the stream, each of which is a size byte, and puts the read fields into the character array specified by ptr, returns the number of actually read fields. Reading

When the number of fields to be retrieved is smaller than num, an error may occur during function calling or reading the end of the file. Therefore, you must call feof () and ferror () to determine.

Write () writes n fields from the array referred to by the buffer ptr to the stream. Each field is in size and returns the number of actually written fields.

In addition, the C-database functions provide positioning capabilities in the read/write process, including

Int fgetpos (FILE * stream, fpos_t * pos );

Int fsetpos (FILE * stream, const fpos_t * pos );

Int fseek (FILE * stream, long offset, int whence );

.

Close

Using the C library function to close a file is still a simple operation:

Int fclose (FILE * stream );

Routine: Use the C library function to implement the routine in section 2nd.

# Include <stdio. h>

# Define LENGTH 100

Main ()

{

FILE * fd;

Char str [LENGTH];

 

Fd = fopen ("hello.txt", "w +");/* Create and open a file */

If (fd)

{

Fputs ("Hello, Software Weekly", fd);/* write the Hello, software weekly string */

Fclose (fd );

}

 

Fd = fopen ("hello.txt", "r ");

Fgets (str, LENGTH, fd);/* Read File Content */

Printf ("% s" n ", str );

Fclose (fd );

}

4. Summary

The Virtual File System provided by Linux provides a unified interface for a variety of file systems. There are two methods for file programming in Linux: Calling Based on Linux systems and C-library functions. These two

The file operations involved in programming include creating, opening, reading, writing, and closing, and locating random files.

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.