I/O file library

Source: Internet
Author: User
Tags control characters rewind

There are several factors that affect access to grayscale files:
1. access permissions are specified only when files are created.
2. umask affects the access permission of the created file. The flag in the open call is a request for setting the object access permission. Whether the requested permission is set depends on the current umask value.

1 umask: When a file is created, a mask is set for the file access permission.

1 owner
2 group
3. Other users

0. Allow all permissions.
4. Read prohibited
2. Write prohibited
1. Execution prohibited

2 close system call: Terminate the association between a file descriptor Fildes and its corresponding file. Fildes is released and can be reused.
# Include <unistd. h>
Int close (INT Fildes)
0: Successful
-1: Failed

3 IOCTL call: provides an interface for controlling the behavior of device machine descriptors and configuring underlying services.
POSIX defines IOCTL calls for stream

A program for copying files (copying the content in file. In to file. out)
In = open ("file. In", o_rdonly); // open an existing file. In and set it to readonly.
Out = open ("file. Out", o_wronly | o_creat, s_irusr | s_iwusr); // create a writable file. Out
While (read (in, & C, 1) = 1) // read 1 byte from file. In And put it in C
Write (Out, & C, 1); // put one byte in C into file. Out.

Run: timeformat = "" time./copy_system // use time to measure the running time.
0.00 user 0.00 system. 00 elapsed 50% CPU

3.4.5 other system calls related to file management
1 lseek System Call: sets the read/write pointer of the file descriptor, which can be used to set the next read/write location of the file. The read/write pointer can be set to an absolute position in the file, or to a relative position relative to the current position or tail.

# Include <unistd. h>
# Include <sys/types. h>
Off_t lseek (INT Fildes, off_t offset, int whence );
Offset: used to specify the position
Whence: used to define the Offset Value
The returned value is the byte offset from the file header to the object pointer.
-1: Return failure

Seek_set: offset is the absolute value.
Seek_cur: Current
Seek_end: End

3.5 standard I/O Library
The standard I/O Library and its header file stdio. h provide a common interface for underlying I/O system calls. In the I/O Library, the peer object corresponding to the underlying file descriptor is called a stream and is implemented as a file pointer.
When the program starts, three file streams are automatically opened. stdin, stdout, and stderr respectively correspond to the underlying file descriptors 0, 1, and 2.

3.5.1 fopen function
# Include <stdio. h>
File * fopen (const char * filename, const char * mode );
Fopen open the file specified by the filename parameter and associate it with a file stream. Mode specifies the file opening mode.
If the file is successfully opened, the pointer to the file stream is returned. Otherwise, null is returned.
R: readonly
W: Write. The length of the file is reduced to 0.
A: Write. The new content is appended to the end of the file.
R +: open (read/write) in a modified way to open a readable file. The file must exist.
W +: open a readable/writable file. If the file exists, delete the file content. If the file does not exist, create the file.
A +: open a read/write file by attaching it. If the file exists, append it to the end. If the file does not exist, create the file.
You can add B to all of the above types of strings, such as Rb, RB +, R + B. Adding B tells the function library that the files opened are binary files rather than plain text files.
Simple Example
# Include <stdio. h>
Main ()
{
File * FP;
Fp = fopen ("hi.txt", "A + ");
If (FP = NULL)
Printf ("cannot open file! /N ");
Printf ("open file! /N ");
Fclose (FP );
}

3.5.2 fread Function
Size_t fread (void * PTR, size_t size, size_t nitems, file * stream); <-------------------------
Reads data from a file stream. Data is read from stream to the data buffer specified by PTR. Size specifies the length of each data record. The counter nitems provides the number of records to be transferred.
When successful, the return value is the number of records read into the data buffer. When the end of the file is reached, the returned value is less than nitems

3.5.3 fwrite Function
Size_t fwrite (const void * PTR, size_t size, size_t nitems, file * strream) ----------------------->
3.5.4 fclose Function
Int fclose (File * stream): closes the specified file stream so that all data that has not been written is written. The maximum number of available File streams is 8.
Int fflush (File * stream): writes all the unwritten data in the file stream immediately. Do not use it before fclose ()
Int fseek (File * stream, long int offset, int whence): Specifies a location for the next read/write operation in the file stream
Offset: used to specify the position
Whence: used to define the Offset Value
0: Success-1: Failure
Int fgetc (File * Stream)

File * stream; // file pointer
Long offset; // offset
Fpos_t Pos;
Stream = fopen ("/etc/passwd", "R"); // open/etc/passwd in read-only mode
Fseek (stream, 5, seek_set); // specifies the read/write location of a file stream, starting from the first five locations of the file.
Printf ("offset = % d/N", ftell (Stream); // ftell (File * stream) gets the current read/write location of the file stream
Rewind (Stream); // rewind (File * stream) resets the file stream's read/write position to start with the file
Fgetpos (stream, & Pos); // fgetpos (File * stream, fpos_t * POS) reads the stream's read location, and Pos returns the read location
Printf ("offset = % d/N", POS); // POS returns the read/write position of fgetpos
POs. _ Pos = 10; // used to set the offset, as in the fseek offset and seek_set
Fsetpos (stream, & Pos); // fsetpos (File * stream, fpos_t * POS) POS is the read/write location of the volume, and stream is the file stream
Printf ("offset = % d/N", ftell (Stream ));
Fclose (Stream );

Fgetc (File * stream): Read a character from the file indicated by stream. EOF is returned at the end of the file, and the read character while (C = fgetc (FP) is returned ))! = EOF)
GETC (File * stream): Same as fgetc, but GETC () is a macro definition, not a real function call.
Getchar (): reads a character from the keyboard, converts the character from unsigned char to int, and returns int c = getchar ();

Fputc (int c, file * stream): converts C to unsigned char and writes it to the file specified by stream. A successful character is returned. Fputc (A [I], FP );
Putc (int c, file * stream): Same as fputc (), but putc () is a macro definition, not a real function call.
Putchar (int c): displays C on the screen

Char * fgets (char * s, int size, file * stream): read characters from the file referred to by stream to the memory space referred to by S. It is known that a line break occurs, and the end of the file, or the size-1 byte ends with null as the string. S is returned successfully, and null is returned if the request fails. <--------------------------
Int fputs (char * s, file * stream): writes the string indicated by S to the file indicated by stream -------------------------->
Char * gets (char * s): read characters from the keyboard coexist to the memory space indicated by s until a line break or file tail occurs, S is returned successfully, and null is returned if a failure occurs.
Int puts (const char * s): writes S to the screen and returns the number of written characters. EOF is a failure.

3.6 format input and output
Int printf (const char * format ,..)
The format string contains three character types:
1. General text, accompanied by direct output.
2 ASCII control characters,/t,/N, etc.
3 Format Escape Character: % format character % [flags] [width] [. prec] Type
Types
1 integer
% D: signed decimal
% U: Unsigned decimal
% O: Unsigned gossip
% X: in hexadecimal notation, expressed as abcdef
% X: in hexadecimal notation (abcedf)
2 floating point number
% F: Double Type decimal, 6 decimal places
% E: outputs a double-precision floating point number using scientific notation
0.001234589: 1.234589e-03
985345.14502: 9.853451e + 05
% G: outputs a double-precision floating point number in a general format.
3 Characters and strings
% C: unsigned char
% S: The parameter pointing to the string will be output word by word, knowing that null appears
Prec situations
1. Minimum number of digits of a positive integer
2. It indicates the number of decimal places in the floating point number.
3. the maximum length of a string in % s format
5. If it is *, the value of the next parameter is the maximum length.
Width is the minimum length of the output. If the output parameter is not a value but *, it indicates that the next parameter is treated as the output length.
The number of actual output characters is returned. If the output fails, the value-1 is returned.

% 10 s "hello" | Hello |
%-10 s "hello" | Hello |
% 10 days 1234 | 1234 |
%-10D 1234 | 1234 |
% 010d 1234 |

Int I = 150;
Double K = 3.14156;

Printf ("% 10.4f/N", k );
Printf ("% 4D/N", I );
Printf ("%-4D/N", I );
Printf ("% 010d/N", I );
Printf ("% 10.4f/N", k );
Printf ("% * s/n", 10, "hello"); // remove 10 digits from the right with the string added

3.1416
150
150
0000000150
3.1416
Hello

Right alignment of positive numbers
Negative number left alignment
The data starting with 0 must be filled with numbers 0.
For
Printf ("% 3 s", "abcdefg"); // abcdefg

Int fprintf (File * stream, const char * Format...): output results in format to the file specified by stream, until '/0' appears.
Int I = 150;
Int J =-100;
Double K = 3.14159;
File * FP;
Fp = fopen ("file. In", "A + ");
Fprintf (FP, "% d % G % x/N", J, K, I );

Int sprintf (char * STR, const char * Format...): format the data according to the format, copy the result to the string array specified by the STR parameter, and know that it appears ('/0 ')

Char * A = "this is string! ";
Char Buf [80];
Sprintf (BUF, ">>> % S </N", );
Printf ("% 10 s", Buf); // >>> this is string! <

3.6.2 scanf, fscanf, sscanf
Int scanf (const char * Format...): format the input data according to the format.
% [*] [Size] [l] [H] Type
*: Ignore and not save parameter data
Size: the length of data that can be input by a parameter.
L: the input data values are stored as long int and double.
H: The input data is stored in short Int.
Type
Contains parameters in printf
[] Read data, but only characters in parentheses are allowed. For example, [A-Z]
[^] Characters in parentheses are not allowed to read data. For example, [^ A-Z]
% Read one %

This is a simple data input.
Char s [256];
Int N;
Float F;
Char C;
Scanf ("Hello, % d, % G, % C, % [^/n]", & N, & F, & C, S );
Printf ("Hello, % d, % G, % C, % s", N, F, C, S );

Solution 1:
Input: 1234, 5.678, X, string to the end

Output: Hello, 3,-9.59892e + 32, ","

Solution 2:
Input: Hello, 1234, 5.678, X, string to the end
Output: Hello, 1234, 5.678, X, string to the endyaozhangjun @ yaozhangjun-desktop :~ /Progm $

Solution 3: Change scanf to scanf ("Hello, % d, % G, % C, % [^/n]/n", & N, & F, & C, s );
Input: Hello, 1234, 5.678, X string to the end
Output: Hello, 1234, 5.678, X, �j ۷ yaozhangjun @ yaozhangjun-desktop :~ /Progm $

Death
In addition, if you want to enter a string, you must write % [^/n]. Otherwise, the previous data will be exhausted.

Scanf ("% 5 [A-Z]", S );
Input abcdefg and output ABCDE
Input AB $ % ^ makdi output AB

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.