Summary of fgets and fputs, fread and fwrite, fscanf, and fprintf Functions

Source: Internet
Author: User
Tags constant definition ranges rewind

String read/write functions fgets and fputs 1. The function of reading string functions fgets is to read a string from a specified file to a character array. The function is called in the form: fgets (character array name, N, file pointer); where N is a positive integer. It indicates that the number of characters read from a file cannot exceed n-1. Add the end string sign '\ 0' after the last character '. For example, fgets (STR, N, FP); reads n-1 characters from the file indicated by FP and sends them to the STR array. [Example 10.4] Read a 10-character string from the e10_1.c file. # Includemain () {file * FP; char
STR [11]; If (FP = fopen ("e10_1.c", "RT") = NULL) {printf ("cannot open file strike any key exit! "); Getch (); exit (1);} fgets (STR, 11, FP); printf (" % s ", STR); fclose (FP );} in this example, a string array of 11 characters is defined. After the e101.c file is opened in the text file mode, 10 characters are read from it and sent to the STR array, add '\ 0' to the last cell of the array, and then display the output STR array on the screen. The output 10 characters are exactly 10.1 characters. Program The first 10 characters. Fgets functions are described as follows: 1.
If a linefeed or EOF is encountered before the n-1 characters are read, the reading ends. 2. The fgets function also has a return value, whose return value is the first address of the character array. 2. The function of writing the string function fputsfputs is to write a string to the specified file. The call form is fputs (string, file pointer). The string can be a String constant, it can also be a character array name or a pointer variable, such as fputs ("ABCD", FP). It means to write the string "ABCD" into the file specified by FP. [Example 10.5] append a string to the string created in example 10.2. # Includemain () {file * FP; char
Ch, St [20]; If (FP = fopen ("string", "At +") = NULL) {printf ("cannot open file strike any key exit! "); Getch (); exit (1);} printf (" input a string: \ n "); scanf (" % s ", St); fputs (St, FP); rewind (FP); CH = fgetc (FP); While (Ch! = EOF) {putchar (CH); CH = fgetc (FP);} printf ("\ n"); fclose (FP );}
In this example, a string must be added at the end of the string file. Therefore, the string file is opened in the append-read-write mode in line 2 of the program. Enter a string and use the fputs function to write the string to the file. In the 15 lines of the program, use the rewind function to move the internal position pointer of the file to the beginning of the file. Then go to the loop to display all the content in the current file one by one. The data block read/write functions fread and fwritec also provide read/write functions for the entire data block. It can be used to read and write a group of data, such as an array element and a value of a structure variable. The calling method of the read data block function is fread (buffer, size, Count, FP). The Calling method of the write data block function is as follows:
Fwrite (buffer, size, Count, FP); buffer is a pointer. In the fread function, it indicates the first address to store the input data. In the fwrite function, it indicates the first address of the output data. Size indicates the number of bytes of the data block. Count indicates the number of data blocks to read and write. FP indicates the file pointer. For example: fread (FA, FP); it means that four bytes (one real number) are read each time from the file indicated by FP and sent to the real array fa, read five consecutive times, that is, read five real numbers into fa. [Example 10.6] input two student data from the keyboard, write them into a file, and read the data of the two students on the screen. # Includestruct
Stu {char name [10]; int num; int age; char ADDR [15];} Boya [2], boyb [2], * PP, * QQ; Main () {file * FP; char ch; int I; pp = Boya; QQ = boyb; If (FP = fopen ("stu_list", "WB +") = NULL) {printf ("cannot open file strike any key exit! "); Getch (); exit (1);} printf (" \ ninput data \ n "); for (I = 0; I <2
I = "" pp = "" scanf = "" s = "" d = "" d = "" s = "" PP-= ""> name, & PP-> num, & PP-> Age, PP-> ADDR); pp = Boya; fwrite (PP, sizeof (struct Stu), 2, FP ); rewind (FP); fread (QQ, sizeof (struct Stu), 2, FP); printf ("\ n \ nname \ tnumber age ADDR \ n "); for (I = 0; I <2 I = "" QQ = "" printf = "" s = "" t = "" 5d = "" 7d = ""
S = "" N = "" QQ-= ""> name, QQ-> num, QQ-> Age, QQ-> ADDR); fclose (FP );} in this example, the program defines a structure Stu, indicating two arrays Boya and boyb, and two structure pointer variables PP and QQ. PP points to Boya, QQ points to boyb. Line 2 of the program opens the binary file "stu_list" in read/write mode, enters two student data, writes it to the file, and moves the internal position pointer of the file to the beginning of the file, after reading two pieces of student data, it is displayed on the screen. Format the read/write functions fscanf and fprintffscanf. The fprintf function is similar to the scanf and printf functions used earlier.
Functions have similar functions. They are all formatted read/write functions. The difference between the fscanf function and fprintf function is that the Read and Write objects are not keyboard and display, but disk files. The call formats of these two functions are: fscanf (File pointer, Format String, input table column); fprintf (File pointer, Format String, output table column); for example: fscanf (FP, "% d % s", & I, S); fprintf (FP, "% d % C", J, CH ); the fscanf and fprintf functions can also be used to solve the problem in the case of 10.6. Shows the modified program in example 10.7. [Example 10.7] # includestruct Stu {char
Name [10]; int num; int age; char ADDR [15];} Boya [2], boyb [2], * PP, * QQ; Main () {file * FP; char ch; int I; pp = Boya; QQ = boyb; If (FP = fopen ("stu_list", "WB +") = NULL) {printf ("cannot open file strike any key exit! "); Getch (); exit (1);} printf (" \ ninput data \ n "); for (I = 0; I <2 I = ""
Pp = "" scanf = "" s = "" d = "d =" s = "" PP-= ""> name, & PP-> num, & PP-> Age, PP-> ADDR); pp = Boya; for (I = 0; I <2 I = "" pp = "" fprintf = "" FP = "" s = "" d = "" d = "" s = "" N = "" PP -= ""> name, PP-> num, PP-> Age, PP-> ADDR); rewind (FP); for (I = 0; I <2 I = "" QQ = "" fscanf = "" FP = "" s = "" d = "" d = "" s = ""
N = "" QQ-= ""> name, & QQ-> num, & QQ-> Age, QQ-> ADDR ); printf ("\ n \ nname \ tnumber age ADDR \ n"); QQ = boyb; for (I = 0; I <2 I = "" QQ = "" printf = "" s = "" t = "" 5d = "" 7d = "" s = "" N = "" QQ -= ""> name, qq-> num, QQ-> Age, QQ-> ADDR); fclose (FP);} compared with example 10.6, in this program, the fscanf and fprintf functions can read and write only one structured array element at a time. Therefore, they use loop statements to read and write all array elements.
Note that the pointer variable PP, QQ, has changed their values cyclically, so they are re-assigned the first address of the array in line 25 and 32 of the program. The read and write methods described earlier in the document are sequential reading and writing. That is, the read and write operations can only start from the beginning and read and write data sequentially. However, in practice, it is often required that a specified part of the read-only file be written. To solve this problem, the position pointer inside the file is moved to the location where the file needs to be read and written before reading and writing. This read and writing is called random read and write. The key to achieving random read/write is to move the location pointer as required, which is called file location. There are two main functions used to locate and move the internal position pointer of a file, namely the rewind function and the fseek function. The rewind function has been used multiple times before. Its call form is:
Rewind (File pointer); it is used to move the position pointer inside the file to the beginning of the file. The following describes the fseek function. The fseek function is used to move the internal position pointer of a file. The call form is fseek (File pointer, displacement, starting point). The "file Pointer" points to the object to be moved. "Displacement" indicates the number of bytes to move. The displacement is long data, so that no error occurs when the file length is greater than 64 KB. When a constant is used to represent the displacement, the suffix "L" is required ". The "Starting Point" indicates where to start the calculation of the displacement. There are three defined starting points: the first part of the file, the current position, and the end of the file. The representation is shown in Table 10.2. The starting point represents the symbol, number, and header of the file.
Seek-set 0 current position seek-cur 1 file end seek-end 2 For example: fseek (FP, 100l, 0 ); it means to move the position pointer to the first 100 bytes of the object. It must be noted that the fseek function is generally used for binary files. In a text file, the conversion is performed, so the location of the calculation is often incorrect. After moving the pointer, you can use any of the read/write functions described earlier. Generally, fread and fwrite functions are commonly used to read and write data blocks. The following example describes the random read/write operations of a file. [Example 10.8] read the data of the second student in the student file Stu list. # Includestruct
Stu {char name [10]; int num; int age; char ADDR [15];} Boy, * QQ; Main () {file * FP; char ch; int I = 1; QQ = & boy; If (FP = fopen ("stu_list", "rb") = NULL) {printf ("cannot open file strike any key exit! "); Getch (); exit (1);} rewind (FP); fseek (FP, I * sizeof (struct Stu), 0); fread (QQ, sizeof (struct
Stu), 1, FP); printf ("\ n \ nname \ tnumber age ADDR \ n "); printf ("% s \ t % 5d % 7D % s \ n", QQ-> name, QQ-> num, QQ-> Age, QQ-> ADDR );} the stu_list file has been created by the program in example 10.6. This program reads the data of the second student by random reading. The program defines boy as a stu type variable, and QQ as a pointer to boy. Open the file by reading the binary file, and the program moves the file location pointer in line with 22nd. The value of I is 1, which indicates that starting from the file header, the length of an Stu type is moved, and then the data read is the data of the second student. File moderation functions commonly used in C language include the following. I. File end detection function feof function call format:
Feof (File pointer); function: determines whether the file is at the end of the file. If the file ends, the return value is 1; otherwise, the value is 0. Ii. file read/write error detection function ferror function call format: ferror (File pointer); function: checks whether an error occurs when a file is read and written using various input/output functions. If the return value of ferror is 0, it indicates no error; otherwise, it indicates an error. 3. Set the file error mark and file end sign to 0. clearerr function call format: clearerr (File pointer). function: This function is used to clear the error mark and file end sign so that they are 0 values. C library file C system provides a variety of system files, called library files. C library files are divided into two types, one is files with the extension of ". H", called header files,
We have used the preceding command multiple times. The ". H" file contains constant definition, type definition, macro definition, function prototype, and various compilation and selection settings. Another type is the function library, which includes the goals of various functions. Code For the user to call in the program. When a library function is called in a program, the ". H" file of the function prototype must be included before the function is called. All database functions are provided in the appendix. Alloc. h indicates memory management functions (such as allocation and release ). Assert. h defines assert debugging macros. BiOS. h describes the various functions that call the IBM-PC rom bios subroutine. Conio. h indicates that each function of the I/O subprogram of the DOS console is called. Ctype. h
Contains information about character classification and conversion of name classes (such as isalpha and toascii ). Dir. h contains the Directory and path structures, macro definitions, and functions. Dos. h defines and describes some constants and functions called by msdos and 8086. Erron. h defines the entrustment of the error code. Fcntl. h defines the symbolic constant used to connect to the Open Library subroutine. Float. h contains some parameters and functions related to floating point operations. Graphics. h describes various functions related to graphic functions, constant definitions of graphic error codes, various color values of different drivers, and some special structures used by functions. Io. h
Contains the structure and description of low-level I/O subprograms. Limit. h contains environment parameters, compilation time limits, number ranges, and other information. Math. h describes the mathematical operation functions, and defines the huge Val macro, which describes the special structures used by matherr and matherr subprograms. Mem. h indicates some memory operation functions (most of them are also described in string. h ). Process. h describes the various functions of process management, spawn... And exec... Function structure description. Setjmp. h defines the JMP Buf types used by longjmp and setjmp functions. Share. h
Defines the parameters of the file sharing function. Signal. h defines the SIG [ZZ (Z] [zz)] ign and SIG [ZZ (Z] [zz)] DFL constants, indicating the rajse and signal functions. Stdarg. h defines the macro of the read function parameter table. (Such as vprintf and vscscarf functions ). Stddef. h defines some common data types and macros. Stdio. h defines the standard and extended types and macros defined by kernighan and Ritchie in UNIX System V. Standard I/O predefined streams: stdin, stdout, and stderr are also defined to describe the I/O Stream subprograms. Stdlib. h
Describes some common subprograms: conversion subprograms, search/sort subprograms, etc. String. h describes some string operations and memory operation functions. Sys \ Stat. h defines some symbolic constants used to open and create files. Sys \ types. h describes the ftime function and timeb structure. Sys \ time. h defines the time type time [ZZ (Z] [zz)] T. Time. h defines the structure of the time conversion subprograms asctime, localtime, and gmtime, the types used by ctime, difftime, gmtime, localtime, and stime, and provides prototype of these functions. Value. h
Define important constants, including those dependent on machine hardware and constants that are compatible with UNIX System V, including floating point and double-precision value ranges. Address: http://happyshepherd.blog.sohu.com/97482172.html

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.