The most common file read/write

Source: Internet
Author: User

Read/write operations on common files, as shown in the following example:

# Include <stdio. h>
# Include <fcntl. h>
# Include <unistd. h>
# Include <stdlib. h>
# Include <sys/STAT. h>

Int main (){

Char Buf [10];
Int N, FD;
Struct stat file_stat;

Stat ("test", & file_stat );
Printf ("file device number: % d \ n", (INT) file_stat.st_dev );
Printf ("node: % d \ n", (INT) file_stat.st_ino );
Printf ("folder type: % d \ n", (INT) file_stat.st_mode );
Printf ("Number of hard links: % d \ n", (INT) file_stat.st_nlink );
Return 0;

/**
* Read from the standard input by reading the file and write it back to the standard output.
*/
N = read (stdin_fileno, Buf, 10 );
If (n <0 ){
Perror ("read error ");
Exit (1 );
}
Write (stdout_fileno, Buf, N );

/**
* Create an object
*/
FD = open ("test", o_creat, s_irwxu );
Close (FD );

/**
* Write characters to files
*/
FD = open ("test", o_wronly );
N = write (FD, Buf, sizeof (BUF ));
Close (FD );

/**
* Open a common file to read characters
*/
FD = open ("test", o_rdonly );
N = read (FD, Buf, sizeof (BUF ));
Printf ("% s \ n", Buf );
Close (FD );

/**
* Location of the relocation operation
*/
FD = open ("test", o_wronly );
N = lseek (FD, 10, seek_set );
N = write (FD, Buf, sizeof (BUF ));
Close (FD );

/**
* Truncate the file (variable length is also available)
*/
FD = open ("test", o_rdwr );
N = ftruncate (FD, 14 );
Close (FD );

Return 0;
}

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.