File I/O operations in Linux (System I/O)

Source: Internet
Author: User
Tags function prototype

We all know that all the devices under Linux are files, so when we need to use them, we need to open them first, and let's look at the file I/O operations in detail below.

The file I/O used has the following actions: Opening a file, reading a file, writing a file, closing a file, and so on: open, read, write, close, lseek (file pointer offset)

File descriptor: For the kernel, all open files are referenced by a file by descriptor. The file descriptor is a non-negative integer.
When an existing file is opened or a new file is created, the kernel returns a file descriptor to the process.
When a file is read and written, the file is identified using the file descriptor returned by Open/creat, which is passed as a parameter to read or write.

Linux System file descriptor 0 is the standard input, 1 is the standard output, 2 is the standard error, so generally open the file when the file descriptor is starting from 3.

Here read and write are not able to format read and write, if you want to know how to format the file read and write , you can look at my previous writing an essay.

 First, open the file (1) header file #include<sys/types.h>#include<sys/stat.h>#include<fcntl.h>(2) function prototypesintOpen(Const Char*pathname,intflags); Parameters: A, pathname: Open or create a file name, such as"text"B, flags:o_rdonly: Read-only open o_wronly: Write-only open o_rdwr: Read, write open o_creat: If this file does not exist, create it, use O _creat is followed by a file access permission bit, such as O_creat,0777o_append: Append to the end of the file each time O_excl: If O_creat is specified at the same time, and the file already exists, an error occurs, which allows you to test whether a file exists, or if it does not exist, create this file, which makes testing and creating both an atomic Operation O_dsync: Make each write wait for physical I/O The operation is complete, but if the write does not affect the reading of the data just written, there is no need to wait for the file property to be updated O_nonblock: If path refers to a FIFO, a block special file, or a character special file, the This option is for this open operation of the file and subsequent I/O operation set non-blocking mode o_noctty: If path refers to an end device, it is assigned to the control terminal o_sync for this process: make each write wait for physical IThe/O operation is complete, including the i/required to update the file properties that are caused by the writeO O_trunc: If the file exists and is a regular file and read-write or write-only open, then its length truncated to 0, if the file is a FIFO or terminal equipment file, O_trunc flag is ignored, otherwise o_trunc ambiguous O_directory: If pathname does not refer to a directory, an error occurs (3) return Value: Success: File descriptor failed:-1 Second, read the file (1) header file #include <unistd.h>(2) function prototype ssize_tRead(intFdvoid*buf, size_t count); Parameters: A, FD: The file descriptor B, buf: Used to hold the data read from the file in buffer C, count: The number of bytes read (3return Value: Success: Read the number of bytes, if read to the end of the file, then return 0 failure:-1 Third, write the data (1) header file #include <unistd.h>(2) function prototype ssize_tWrite(intFdConst void*buf, size_t count); Parameters: A, FD: The file descriptor B, buf, returned after calling open: Buffer C, Count: The number of bytes written to the data (3return Value: Success: Failed to return the number of bytes written:-1 iv. Closing of files (1) header file #include <unistd.h>(2) function prototypesint Close(intFD); Parameters: A, FD: The file descriptor returned after the call to open , file offset (1) header file #include <sys/types.h>#include<unistd.h>(2) function prototype off_tLseek(intFD, off_t offset,intwhence); Parameters: A, FD: The file descriptor B, offset and parameter whence returned after the call to open, usually set to 0 (according to Thedirective whence asfollows) C, Whence:seek_set: Sets the offset of the file to offset bytes from the beginning of the file Seek_cur: Set the offset of the file to its current value plus offset bytes, offset can is positive or negative seek_end: Sets the file offset to the file length plus offset,offset can be positive or negative (3return Value: Success: Failed to return new file offset:-1

Here's the code:

#include <sys/types.h>#include<sys/stat.h>#include<sys/fcntl.h>#include<stdio.h>#include<errno.h>#include<stdlib.h>#include<unistd.h>#include<string.h>#definePATHNAME "Text.txt"#defineLENGTH 4096voidErrorChar*name)//Error Hints{perror (name); Exit (1);}intMainintargcChar*argv[]) {        intFD;//Storing file descriptors    intSize1;//return value at read operation    intSize//return value on write operation    intOffset//file Offset//Open File    /*O_REWR indicates that the file is open with read and write permission, o_creat means that if the file does not exist, the permission to create a new file created by * is 0777, which is a read-write executable, and O_append writes from the end of the file when writing to the data*/    if(FD = open (pathname,o_rdwr| O_creat| O_append,0777)) == -1) {error ("Open"); }                    CharBuf[length]; Bzero (BUF,sizeof(BUF)); //reading data from a file    if(size1 = Read (Fd,buf,sizeof(BUF))) == -1) {error ("Read"); } printf ("%s\n", BUF); CharBuf1[length] ="Small World"; //writing data to a file   if(size = Write (FD,BUF1,sizeof(BUF))) == -1) {error ("Write"); }    CharBuf3[length] ="Hello World"; if(size = Write (FD,BUF3,sizeof(BUF3))) == -1) {error ("Write"); }        //Because the file pointer is shifted to the end of the file when the data is written to the file, the file pointer is shifted to the file header, which facilitates the following reading    if(offset = Lseek (FD,0, seek_set)) = =-1) {error ("Lseek"); } bzero (BUF,sizeof(BUF)); if(size1 = Read (Fd,buf,sizeof(BUF))) == -1) {error ("Read"); } printf ("%s\n", BUF); //Close FileClose (FD); return 0;}
View Code

This is the result of my running on Ubuntu, but there is a strange place when I opened the file under Windows did not see the back of the content, and garbled, in Ubuntu under the Cat command can see all the contents of the file, and no garbled

    • Open a file with the cat command
    • Terminal output
    • Open under Windowns

File I/O operations in Linux (System I/O)

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.