search

Linux file operations

Sep 13, 2018 pm 06:24 PM
linux

The example of this article describes the method of interactive execution of python file reading and writing operations and Linux shell variable commands. Share it with everyone for your reference. The details are as follows:

Related system calls for file operations

Create

int creat(const char *filename, mode_t mode);
Parameter mode specifies new The access permission of the file, which together with umask determines the final permission of the file (mode & umask), where umask represents some access permissions that need to be removed when the file is created. It only affects read, write and execution permissions. The calling function is int umask (int newmask).

Open

int open(const char *pathname, int flags);
pathname is the file name we want to open (including the path name, the default is the current path)

flags Open flag

  • O_RDONLY Open the file in read-only mode


  • O_WRONLY Open the file for writing only


  • O_RDWR Open the file for reading and writing Open the file as


  • O_APPEND Open the file as append


  • O_CREAT Create a file


  • ##O_EXEC If O_CREAT is used And the file already exists, an error will occur


  • ##O_NOBLOCK Open a file in a non-blocking manner

  • O_TRUNC If the file already exists, delete the contents of the file
  • int open(const char *pathname, int flag, mode_t mode)

When flag is O_CREATE, specify the mode flag to indicate file access permissions

    S_IRUSR Users can read

  • ##S_IWUSR User can write

  • S_IXUSR User can execute

  • ##S_IRWXU User can read, write and execute

  • ##S_IRGRP group can read

  • S_IWGRP group can write

  • S_IXGRP group can execute

  • The S_IRWXG group can read, write, and execute

  • S_IROTH Others can read

  • ## S_IWOTH Others can write


  • #S_IXOTH Others can execute


  • S_IRWXO Others can Read, write, execute


  • S_ISUID Set the user’s execution ID


  • S_ISGID Set the execution ID of the group


  • The mode flag can also use numbers to represent file permissions:
  • Each number can take the value of 1 (execution permission), 2 (write permission), 4 (read permission), 0 (none), or the sum of these values.

The first digit indicates setting the user ID

  • The second digit indicates Set the group ID


  • The third digit represents the user’s own permission bit


  • The fourth digit indicates the group’s permissions


  • The fifth digit represents the permissions of others


  • open("test", O_CREAT, 10705);
  • The above statement is equivalent to:

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

Read and write

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

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

Parameter fd file descriptor, buf is the pointer to the buffer, length is the size of the buffer (in bytes), and the return value is The actual number of bytes read and written.


read() reads length bytes from the file specified by the file descriptor fd into the buffer pointed by buf. The return value is the actually read bytes. Number

  • write() implementation will write length bytes from the buffer pointed to by buf to the file descriptor In the file pointed to by fd, the return value is the number of bytes actually written.


  • Positioning

  • For random files, we can randomly specify the location to read and write:
int lseek(int fd, offset_t offset, int whence);

lseek() moves the file read-write pointer relative to whence by offset (can be a negative value) bytes. When the operation is successful, the position of the file pointer relative to the file header is returned.

The parameter whence can use the following values:

SEEK_SET: relative to the beginning of the file.
SEEK_CUR: The current position of the relative file read and write pointer.

SEEK_END: ​​Relative to the end of the file.

Close

int close(int fd);

File operation of C library function-independent of the specific operating system platform

Create and open

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

fopen() realizes opening the specified file filename, where the mode is the open mode, Linux The system does not distinguish between binary files and text files.

The value of mode


r, rb is opened in read-only mode

  • w, wb Open in write-only mode. If the file does not exist, the file is created, otherwise the file is truncated


  • a, ab are opened 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 are opened in read and write mode. If the file does not exist, a new file is created, otherwise the file is truncated


  • a, a b, ab for reading and appending way to open. If the file does not exist, create a new file

Read and write

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);
int fsetpos(FILE *stream, fpos_t *pos);
nt fsetpos(FILE *stream, const fpos_t *pos);
int fseek(FILE *stream, long offset, int whence);

  • fread() implements reading n fields from stream, each The field is size bytes, and the read fields are put into the character array pointed by ptr, and the actual number of fields read is returned.


  • write() implements writing n fields from the array pointed to by buffer ptr to stream, each time The length of each field is size bytes, and the number of fields actually written is returned.

Close

int fclose (FILE *stream);

Linux file system directory structure

Linux file operations

  • /bin----stores the most commonly used basic commands, such as ls , cp, mkdir, etc., the files in this directory are all executable.


  • /boot----Some core files used when starting Linux, including some connection files and image files, Such as vmlinuz, initrd.img


  • /dev----device file storage directory, the application program passes these files Read, write and control the actual device.


  • /etc----Configuration files and subdirectories required for system management, such as user account and password configuration files .


  • /home----The home directory of ordinary users. Each user has his own directory. Generally, The directory name is named after the user's account.


  • /lib----Library file storage directory, the most basic dynamic link shared library of the system, similar to Windows DLL file inside.


  • /lost found----usually empty, when the system crashes unexpectedly or the machine shuts down unexpectedly Some file fragments will be generated and placed here.


  • /mnt----It is convenient for users to temporarily mount other file systems, such as mounting the optical drive on /mnt/, enter this directory to view the contents of the CD-ROM drive


  • media----automatically recognize some Devices are mounted to this directory, such as USB drives, CD-ROM drives, etc.


  • /opt----The directory where additional installation software is stored on the host


  • /proc----When the operating system is running, process and kernel information (such as CPU, hard disk partition, memory information, etc.) are stored here. It is a mapping of system memory and exists in memory. System information can be obtained by directly accessing this directory.


  • /root----The home directory of the super privileged user


  • /sbin----The directory where executable commands for super privileged users are stored. Ordinary users do not have permission to execute commands in this directory


  • /tmp-----Storage temporary files.


  • /usr-----Directory where system applications and files (such as commands and help files) store programs , similar to the program files directory under Windows.


  • /var-----Directories that are frequently modified are placed in this directory, such as log files


  • /sys----

    An intuitive reflection of the kernel device tree. When a kernel object is created, the corresponding files and directories are also created in the kernel object subsystem.


  • /initrd---If the initrd image is used as a temporary root file system during the boot process, After executing /linuxrc to mount the real root file system, the original initial RAM file system is mapped to the /initrd directory.

Linux file system and device driver

Related recommendations:

linux Parent directory permissions affect subdirectory files Operation

How to interactively execute python file read and write operations with linux shell variable commands

The above is the detailed content of Linux file operations. For more information, please follow other related articles on the PHP Chinese website!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Linux: A Deep Dive into Its Fundamental PartsLinux: A Deep Dive into Its Fundamental PartsApr 21, 2025 am 12:03 AM

The core components of Linux include kernel, file system, shell, user and kernel space, device drivers, and performance optimization and best practices. 1) The kernel is the core of the system, managing hardware, memory and processes. 2) The file system organizes data and supports multiple types such as ext4, Btrfs and XFS. 3) Shell is the command center for users to interact with the system and supports scripting. 4) Separate user space from kernel space to ensure system stability. 5) The device driver connects the hardware to the operating system. 6) Performance optimization includes tuning system configuration and following best practices.

Linux Architecture: Unveiling the 5 Basic ComponentsLinux Architecture: Unveiling the 5 Basic ComponentsApr 20, 2025 am 12:04 AM

The five basic components of the Linux system are: 1. Kernel, 2. System library, 3. System utilities, 4. Graphical user interface, 5. Applications. The kernel manages hardware resources, the system library provides precompiled functions, system utilities are used for system management, the GUI provides visual interaction, and applications use these components to implement functions.

Linux Operations: Utilizing the Maintenance ModeLinux Operations: Utilizing the Maintenance ModeApr 19, 2025 am 12:08 AM

Linux maintenance mode can be entered through the GRUB menu. The specific steps are: 1) Select the kernel in the GRUB menu and press 'e' to edit, 2) Add 'single' or '1' at the end of the 'linux' line, 3) Press Ctrl X to start. Maintenance mode provides a secure environment for tasks such as system repair, password reset and system upgrade.

Linux: How to Enter Recovery Mode (and Maintenance)Linux: How to Enter Recovery Mode (and Maintenance)Apr 18, 2025 am 12:05 AM

The steps to enter Linux recovery mode are: 1. Restart the system and press the specific key to enter the GRUB menu; 2. Select the option with (recoverymode); 3. Select the operation in the recovery mode menu, such as fsck or root. Recovery mode allows you to start the system in single-user mode, perform file system checks and repairs, edit configuration files, and other operations to help solve system problems.

Linux's Essential Components: Explained for BeginnersLinux's Essential Components: Explained for BeginnersApr 17, 2025 am 12:08 AM

The core components of Linux include the kernel, file system, shell and common tools. 1. The kernel manages hardware resources and provides basic services. 2. The file system organizes and stores data. 3. Shell is the interface for users to interact with the system. 4. Common tools help complete daily tasks.

Linux: A Look at Its Fundamental StructureLinux: A Look at Its Fundamental StructureApr 16, 2025 am 12:01 AM

The basic structure of Linux includes the kernel, file system, and shell. 1) Kernel management hardware resources and use uname-r to view the version. 2) The EXT4 file system supports large files and logs and is created using mkfs.ext4. 3) Shell provides command line interaction such as Bash, and lists files using ls-l.

Linux Operations: System Administration and MaintenanceLinux Operations: System Administration and MaintenanceApr 15, 2025 am 12:10 AM

The key steps in Linux system management and maintenance include: 1) Master the basic knowledge, such as file system structure and user management; 2) Carry out system monitoring and resource management, use top, htop and other tools; 3) Use system logs to troubleshoot, use journalctl and other tools; 4) Write automated scripts and task scheduling, use cron tools; 5) implement security management and protection, configure firewalls through iptables; 6) Carry out performance optimization and best practices, adjust kernel parameters and develop good habits.

Understanding Linux's Maintenance Mode: The EssentialsUnderstanding Linux's Maintenance Mode: The EssentialsApr 14, 2025 am 12:04 AM

Linux maintenance mode is entered by adding init=/bin/bash or single parameters at startup. 1. Enter maintenance mode: Edit the GRUB menu and add startup parameters. 2. Remount the file system to read and write mode: mount-oremount,rw/. 3. Repair the file system: Use the fsck command, such as fsck/dev/sda1. 4. Back up the data and operate with caution to avoid data loss.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software