Input and output with file one, terminalI/O1. Single characterI/o:getchar (), Putchar ()(1)Single character input(Get character):
"Int GetChar ();"
- The return value is the input character (ASCII). can accept any character, including nonprinting characters. When you type more than one character at a time, GetChar starts reading all characters (including carriage returns) one at a time after you press ENTER.
- In some compiled environments, because the scanf () function does not read the carriage return and leaves it in the input queue, the next call to scanf () causes the input to be terminated prematurely before reading the data because it reads the carriage return first, so it is often used after scanf to "GetChar ();" reads and discards the carriage return.
(2)Single character output(Put character):
"int Putchar (int);"
- The return value is the output character, and the parameter is the character to be output (ASCII). is a parameter-containing macro defined in stdio.h.
2. Format input and output (1)formatted output(print format):
"int printf (format control, output table column);"
- The format control is a string constant consisting of a normal (escaped) character, a conversion specifier, and a conversion modifier. Normal (escaped) character direct output (control cursor), the conversion specifier is replaced in order by the amount in the Output table column. The commonly used format specifiers are:
<1>%d%ld integer or Long integer type
<2>%c character type, parameters can be ASCII or single quote characters
<3>%f%LF floating point number, double type commonly used%LF. Default 6 decimal places, automatically rounded
<4>%s String type, no input output '
<5>%e output floating-point numbers using the E-count method (scientific notation)
<6>%x Output 16 binary number,% #x输出0x格式
<7>%o Unsigned 8 binary number
- Conversion modifiers are used to describe formats such as alignment widths.
<1> floating point%m.nf,m is the total width, and the positive number represents the left-aligned negative number for right alignment. The default is to use a space to fill the position, if M's highest bit is 0 with 0 complement.
(2)format Input(scan format)
"Int scanf (format control, Address table column);"
- Format control is similar to the printf function, where the value of% and the middle of the format character represents the number of bits read, and N in%.ns can limit the maximum input length. The Address table column represents the address of the read data store, which can be the &+ variable name, pointer. The direct character array name is not & when the string is read, because it is an address in itself.
- SCANF () In addition to s outside of [...] and [^ ...] can be used for string input. [...] Read Only [...] The characters that appear in the read to the non-contained characters stop reading (can be used to let scanf () also read spaces). [^ ...] On the contrary, read only characters that are not contained in it, and read to the words contained therein to stop reading.
scanfinput mechanism
- The scanf function reads the input character one by one, and stores it in the specified address when it finds an input that matches the format control until it reads the specified number of characters or the first character that does not conform to the format control. However, scanf will leave the first non-conforming character (including a carriage return entered for confirmation input) in the input queue (input buffer), and the next read will start with the discarded character.
- When you call scanf multiple times to remove the carriage return (with the GetChar () function) that was left in the input queue when the last call was made, otherwise scanf will end the read by entering an empty string (the carriage return is the flag that confirms the input) because of the carriage return.
scanffunction return value
- SCANF returns the number of items it successfully read and returns 0 when it fails to read successfully. When reading to the end of the file (end of file) returns EOF (EOF is a constant defined in stdio.h, typically-1). The return value of the scanf can be used to enter data of unknown number or to detect processing exception input. Example: "while (scanf ("%d ", &a)! = EOF)" or "while (scanf ("%d ", &a) = = 1)". Because EOF is usually defined as 1 is considered true, it cannot be used while (scanf (...));.
scanffunction Input String
- The scanf function reads the string by two methods to determine the end of the read. Begins with the first non-whitespace character, reads the specified number of characters, or reads (but does not include) the next blank character.
- * In the middle of the% and format characters indicates lag assignment, scanf will skip these formatting instructions to read the following values directly.
3. String input or output (1)string Input(Get String):
"Char *gets (char *);"
- The gets () function reads the string with the pointer parameter value to the first address to establish a character array. The address returned by get () is the same address that was passed to it, that is, the first address of the character array. A null pointer (NULL) is returned when the read fails or the end of the file is read. Gets () reads all the characters before the newline character and adds a null character (' s ') at the end, giving the first address of the string to the program that called it.
Compared to scanf ():
- The Get () function reads the newline character and discards it, scanf () does not read the newline character and leaves it in the input queue. Gets () reads characters such as spaces and stores them in a string, and scanf () encounters a space that stops reading.
- The Get () function cannot specify the number of input characters, and the extra characters will overflow into adjacent memory areas. The scanf () statement can specify the number of input characters.
(2)string Output(Put string):
"Int puts (const char *str);"
- Outputs a string to the terminal and automatically outputs the number of characters returned by the newline character.
Ii. DocumentsI/O
- File: A collection of data stored on external media. All Devices in Unix (the birthplace of c) are treated as files uniformly (all files).
- Flow: A sequence of data that is read once in a specified order, which can be understood as a sequence of data produced during the input and output process.
- File ID: consists of the file path, the main file name, and the file suffix.
- File buffers: An area in memory where I/O traffic to a file must be filled with buffers before being sent to the program data area (program variables) or external memory.
- File Information area: is a struct variable of type file. The file type is defined in the Stdio.h file to hold the data buffer position, buffer state, file status, and so on.
- File pointer: A pointer to the file information area. Standard file pointer: stdin read from the terminal (keyboard), stdout to the terminal (monitor) output, stderr to the terminal (monitor) to send error messages. They are all definitions of the file pointer (file *) in stdio.h and can be used as parameters to the standard/O function.
- File pointer--File information area--File buffer <-(operating system), file
1. Open Close and redirect files
- The opening and closing of a file is the process of establishing and revoking the file information area associated with the file and the data buffer. The functions that are not described are in the Stdio.h header file.
(1)Open File(File Open):
"(File *) fopen (file name, pattern string);"
1) "R" Read Only "W" write "a" append
2) "B" binary file
3) "+" can read and write
- The three parts are written out sequentially in the same string.
1) must be written out, when the target file does not exist, "R", "a" error, "W" will create a new file.
2) can not be written, the default is to open a text file.
3) can not write, the default is read only write.
1) "r+" begins to read and write on the file header but does not erase the file contents (similar to overtype mode).
2) "A +" to read and write from the end of the file, and automatically move eof (a mode does not automatically move EOF, may not be able to read the appended content in some circumstances, it is recommended A +).
3) "w+" after emptying the file after rewriting.
- The function return value is a pointer to a file that can be used to invoke the file. Returns NULL when open fails.
(2)Close File(file close):
"Int fclose (file pointer);"
- revokes the file information area, the data buffer, and the file pointer no longer points to the file. Turn off successful return 0 otherwise EOF is returned.
- You should first export the data in the buffer to a file and then undo the buffer.
Close all Files:
"Int fcloseall (void);"
(3) redirect(Free open?? ):
"File *freopen (const char* new,const char *type, file *stream);"
which
NEW: The name of the current stream
Type: Open mode (same FileOpen function)
Stream: the original stream.
A pointer to the new stream was returned successfully, and Null was returned.
The read/write of the redirect function to the original stream is replaced by the read and write to the new stream, which allows the program to change its default read-write object without changing other code, which is often used to replace stdin (stdout, stderr) with a file to enable functions such as scanf or printf to read and write to the file.
To recover a standard stream, you can reopen the standard console device file, except that the name of the device file is associated with the operating system.
Dos/windows:
"Freopen (" CON "," R ", stdin);
Linux:
"Freopen ("/dev/console "," R ", stdin);
(4)Flush Buffers(file flush):
"Int fflush (FILE *fp);"
- Sends all the uncommitted data of the buffer to the specified file, which refreshes the buffer. Empties the buffer if the argument is a null pointer.
Flush all buffers:
"Int fflushall (void);"
(5)Exit(exit):
"Void exit (int);"
- Closes all open files and ends the program, equivalent to the return statement in the main function that was originally called (that is, main, which is called by the operating system command, and not another function call). Included in the Stdlib.h header file.
2. Sequential reading and writing of files (1)enter characters from a file(File get character):
"Int fgetc (FILE *fp);"
- Reads a character from the file and returns its ASCII code.
(2)output characters to a file(file put character):
"Int fputc (int ch,file *fp)"
Write character ch to file.
(3)enter a string from a file(File Get string):
"Char *fgets (char *,int,file *FP);"
- Reads a string from the file. The parameter is the string address, the parameter 2 is the maximum number of characters allowed, and if the value is n reads n-1 characters and automatically adds a null character. Parameter 3 reads a file pointer and can use STDIN (standard input) as the parameter when reading data from the keyboard, which is defined in stdio.h. The return value is the same as the gets () function. Fgets () is originally designed to handle file I/O and can also be used to input from the terminal. Fgets () reads to a newline character and stores it in a string without discarding it.
(4)output A string to a file(file put string):
"Int fputs (const *char, FILE *FP)"
- Writes a string to the file. Parameter 1 is the string constant to output, and parameter 2 is the file to write to. You can use STDOUT (standard output) as a parameter for display, which is defined in stdio.h. The function return value is the number of characters that were successfully output.
- File-oriented string input and output statements do not automatically delete and subtract line breaks.
(5)format output to a file(file Print format):
"Int fprintf (file pointer, format string, output table column);"
- Formats the output to a file.
(6)format input from a file(file scanf format):
"Int fscanf (file pointer, format string, Address table column);"
- These file read and write functions also return EOF when they are read to the end of the file, and can refer to the use of the scanf function when entering numbers of indeterminate data and handling exception inputs.
- To read and write a piece of data to a file in a binary way:
- In the program not only need to input and output one data at a time and often need to input and output a set of data (such as an array or struct), C allows to directly copy a piece of memory into the file or copy from the file to memory.
(7)reading data blocks from a file(file read)
"Size_t fread (void *buffer,size_t size, size_t count, FILE *FP);"
(8) Output data block (file write) to files:
"size_t fwrite (const void *buffer,size_t size, size_t count, FILE *FP);"
which
Buffer: The first address of the memory area written out (read from a file) to the file.
Size: The number of bytes per data item to read and write.
Count: The number of data items to read and write.
FP: file pointer.
When you open a file with a binary file open, you can read and write any type of data.
3. Random reading and writing of files
- The sequential reading and writing of the file is read and written according to the data in the physical location of the file, first reading the previous data and then reading the latter data. The random read and write of a file can access data at any location, and obviously this method is much more efficient than sequential read and write. (Array of analogies and reading and writing of linked lists)
- In order to control the file read and write, the system sets the file read-write location tag (short file location tag or file tag) for each file to indicate the location of the next character to read and write. When you open a file, the file tag points to the file header, and when you finish reading and writing, point to the next character prompt (similar to the cursor in Notepad).
Change file read/write Tags: fseek () and Rewind ()
(1)read-write marker positioning(file seek):
"Int fseek (FILE *filename, long int offset, int from);"
which
FileName: Manipulating the File object
Offset: Offsets (Long integer, to add an L to the end of the number), positive values move toward the end of the file, and negative values move toward the beginning of the file.
From: The starting point of the move, defined in C:
0-seek_set file Start
1-seek_cur Current Location
2-seek_end End of File
(2)read-Write token reset(Rewind):
"Void Rewind (FILE *filename);"
- Make the file marker point to the file header. When you open a string in read-write mode, you need to pay special attention to the location of the tag.
(3)determine the location of a file marker(file tell):
"Long int ftell (FILE *fp);"
(4)returns the location of the file location marker(end of file):
"Int feof (FILE *fp);"
- Returns a value other than 0 when the file location tag is at the end of the file, or 0.
(5)file read-write error detection(file error):
"Ferror (FP);"
- Returning 0 means no error, and returning a non-0 value indicates an error.
- When the length of the data is unknown, it is necessary to determine whether or not to reach EOF, because sometimes the side reads the edge processing, when the input function reads to EOF time stop reading does not update the variable, the last set of data can be processed and output two times. At this time not only need to use feof to control the number of cycles, but also to use feof after reading to determine whether to jump out of the loop ahead. In particular, an error occurs when the Fread function reads to EOF and needs to be judged by ferror.
(6)Clear Error Flag(Clear error):
"OID Clearerr (FILE *fp);"
- Place the file error flag and end of file flag at 0. Whenever a file read-write error flag occurs, it persists until the Clearerr,rewind function is called, or the next time the input and output is made.
Three, parameters
1. Parameter passing mechanism:
The computer uses the variable type to present the value of the variable in the stack, but the printf function is read based on the conversion descriptor. If the longer data uses a shorter specifier to read only a portion (a number converted to decimal may become odd), shorter data uses a longer specifier to read the characters in the next memory cell and output unpredictable results.
2. function return value:
The printf function output returns the number of characters in the output (both print and nonprinting characters), and failure returns a negative value that represents the type of failure.
3.* parameters
You can use * instead of numbers when specifying the number of output bits, but there is a corresponding value (constant or variable) in the corresponding position of the output table column.
Four
Input and output with file