Summary of Functions Fgets and fputs, Fread and Fwrite, fscanf, and fprintf usage

Source: Internet
Author: User
Tags constant definition rewind

Summary of Functions Fgets and fputs, Fread and Fwrite, fscanf, and fprintf usage

string read and Write functions fgets and fputs

The function of reading a string function Fgets function is to read a string into a character array from the specified file, in the form of a function call: fgets (character array name, n, file pointer), where n is a positive integer. Indicates that a string that is read from a file does not exceed n-1 characters. After the last character read, add the string end flag ' \ s '. For example: Fgets (STR,N,FP), the meaning is to read from the file referred to in the FP n-1 characters into the character array str.

[Example 10.4] reads a string containing 10 characters from the e10_1.c file.

#include <stdio.h>

#include <conio.h>

#include <stdlib.h>
Main ()
{
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);
}

This example defines a character array str total of 11 bytes, after opening the file e101.c as a read text file, read out 10 characters into the STR array, in the last cell of the array will be added ' \ ', and then display the output str array on the screen. The output of the 10 characters is exactly the first 10 characters of the example 10.1 program.

The Fgets function has a two-point description:

1. Before the n-1 characters are read out, if a newline character or EOF is encountered, the readout ends.

2. The Fgets function also has a return value whose return value is the first address of a character array.

Second, write String function fputs

The function of the fputs function is to write a string to the specified file in the form of: fputs (string, file pointer) where the string can be a string constant, or it can be a character array name, or a pointer variable, for example:

Fputs ("ABCD", FP);

The meaning is to write the string "ABCD" into the file referred to by the FP. [Example 10.5] appends a string to the file created in Example 10.2.

#include <stdio.h>

#include <conio.h>

#include <stdlib.h>
Main ()
{
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);
}

This example requires the string to be written at the end of the string file, so the file string is opened in line 6th of the program to append a read-write text file. It then enters a string and writes it to the file string using the Fputs function. In program 15, use the rewind function to move the file's internal position pointer to the top of the file. Then enter the loop to display the entire contents of the current file one by one.


Data block read-write function fread and fwrite

The C language also provides read and write functions for the entire block of data. Can be used to read and write a set of data, such as an array element, the value of a struct variable, and so on. The general form of a read block function call is: Fread (BUFFER,SIZE,COUNT,FP); The general form of a write block function call is: fwrite (BUFFER,SIZE,COUNT,FP); Where buffer is a pointer to the Fread function, which represents the first address that holds the input data. In the Fwrite function, it represents the first address that holds the output data. A size represents the number of bytes of data block. Count represents the number of block blocks of data to read and write. The FP represents a file pointer.

For example:

Fread (FA,4,5,FP); The meaning is that from the file referred to in the FP, each read 4 bytes (a real number) into the real group FA, read 5 consecutive times, that is, read 5 real numbers into FA.

[Example 10.6] input two student data from the keyboard, write a file, and then read the data of the two students displayed on the screen.

#include <stdio.h>

#include <conio.h>

#include <stdlib.h>
struct 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);
}

This example program defines a structure Stu, illustrates two arrays of structures Boya and BOYB, and two structure pointer variables pp and QQ. PP pointing boya,qq to Boyb. The program line 16th reads and writes the binary file "Stu_list", enters two student data, writes to the file, then moves the file's internal position pointer to the top of the file, and reads out two student data to display on the screen.

Format read-write functions fscanf and fprintf

The FSCANF function, the fprintf function, is similar to the function of the scanf and printf functions used earlier, and is a formatted read-write function. The difference between the two is that the FSCANF function and the read-write object of the fprintf function are not keyboards and monitors, but disk files. The invocation formats for these two functions are: fscanf (file pointers, format strings, input table columns), fprintf (file pointers, format strings, output table columns), for example:

FSCANF (FP, "%d%s", &i,s);
fprintf (FP, "%d%c", j,ch);

The problem of example 10.6 can also be completed with the FSCANF and fprintf functions. The modified program is shown in example 10.7.

[Example 10.7]

#include <stdio.h>

#include <conio.h>

#include <stdlib.h>
struct 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-&GT;ADDR);
Fclose (FP);
}

Compared to example 10.6, the FSCANF and fprintf functions in this program can read and write only one structure array element at a time, so a looping statement is used to read and write all the array elements. Also note that the pointer variable pp,qq because the loop changes their values, so in the program's 25 and 32 rows they are re-assigned to the array's first address.

Random Read and write of files

The previous read and write to the file is sequential read and write, that is, read and write files can only start from scratch, sequentially read and write each data. However, in practical problems, it is often required to read and write only a specified part of a file. In order to solve this problem, the position pointer inside the file can be moved to the location that needs to read and write, and then read and write, which is called Random Read and write. The key to achieving random read and write is to move the position pointer as required, which is called the location of the file. There are two main functions for locating pointers within a file, namely the rewind function and the fseek function.

The rewind function was previously used several times, and its invocation form is: Rewind (file pointer); its function is to move the position pointer inside the file to the top of the file. The following main introduction
The Fseek function.

The Fseek function is used to move the internal position pointer of the file, which is called as: fseek (file pointer, offset, starting point); Where: "File pointer" points to the file being moved. The displacement amount represents the number of bytes moved and requires that the displacement amount be long data so that no error occurs when the file length is greater than 64KB. The suffix "L" is required when the displacement amount is represented by a constant. The start point indicates where the displacement is calculated from, with three starting points: the first file, the current position, and the end of the file.

The representation method is shown in Table 10.2.

The starting point represents the symbolic number representation
──────────────────────────
File First Seek-set 0
Current position Seek-cur 1
End of File Seek-end 2

For example:

Fseek (fp,100l,0); The meaning is to move the position pointer to the first 100 bytes from the file. Also note that the fseek function is commonly used in binary files. In the text file due to the conversion, it is often calculated location error. Random Read and write of a file after moving the position pointer, you can read and write using any of the read-write functions described earlier. Because it is generally read and write a data block, so commonly used fread and fwrite functions. Use the following case to explain the random read and write of the file.

[Example 10.8] Read the second student's data in the student file Stu list.

#include <stdio.h>

#include <conio.h>

#include <stdlib.h>
struct 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-&GT;ADDR);
}

File Stu_list has been established by example 10.6, the program uses a random readout method to read the second student's data. The program defines the boy as the Stu type variable, and QQ is a pointer to the boy. Opens the file as a read binary file, and the 22nd line moves the file position pointer. The I value is 1, which means that the length of a Stu type is moved from the beginning of the file, and then the data that is read out is the second student's data.

File detection function

There are several commonly used file detection functions in C language.

First, the end of the file detection function feof function call format: feof (file pointer);

Function: Determines whether the file is at the end of the file, such as the end of the file, the return value is 1, otherwise 0.

Second, read and write file error detection function ferror function call format: ferror (file pointer);

Function: Check whether the file has errors when reading and writing with various input and output functions. A ferror return value of 0 means that there is no error, otherwise it is wrong.

Iii. file error flag and file End flag 0 function Clearerr function call format: clearerr (file pointer);

Function: This function clears the error flag and the end-of-file flag so that they are 0 values.

C Library File

C system provides a wealth of system files, called library files, c library files are divided into two categories, one is the extension ". h" file, called the header file, in the previous contains the command we have used many times. The ". h" file contains information such as constant definitions, type definitions, macro definitions, function prototypes, and various compilation selection settings. The other is the function library, including the various functions of the target code for the user to call in the program. Typically, when you call a library function in a program, you include the ". h" file where the function prototype resides before the call.

All the library functions are given in the appendix.

ALLOC. H describes memory management functions (allocation, deallocation, and so on).
Assert. H defines the Assert debug macro.
Bios. H describes each function that invokes the IBM-PC ROM BIOS subroutine.
Conio. H describes each function that invokes the DOS console I/O subroutine.
CTYPE. H contains information about the classification and conversion of characters (such as Isalpha and TOASCII, etc.).
DIR. H contains structures, macro definitions, and functions for directories and paths.
Dos. H defines and describes some constants and functions called by Msdos and 8086.
Erron. H defines the mnemonic for the error code.
Fcntl. H defines the symbolic constants when connected to the open Library subroutine.
FLOAT. H contains some parameters and functions for floating-point operations.
GRAPHICS. H describes the functions of the graphical function, the constant definition of the graphical error code, the various color values of the different drivers, and some special structures used in the function.
Io. H contains the structure and description of low-level I/O subroutines.
LIMIT. H contains information such as the environment parameters, compilation time limit, the range of the number.
MATH. H describes the mathematical operation function, and also the HUGE VAL macro, which illustrates the special structure used by Matherr and Matherr subroutines.
Mem. H describes some memory manipulation functions (most of which are also described in STRING.H).
PROCESS. H describes the various functions of process management, spawn ... and exec ... The structure description of the function.
SETJMP. H defines the types of jmp buf used by the longjmp and setjmp functions to illustrate these two functions.
SHARE. H defines the parameters of the file share function.
SIGNAL. H defines Sig[zz (z] [zz)]ign and Sig[zz (z] [zz)]DFL constants, stating RAJSE and signal two functions.
Stdarg. H defines a macro that reads the function parameter table. (such as the Vprintf,vscarf function).
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. Also defines standard I/O pre-defined streams: Stdin,stdout and stderr, which describe I/O stream subroutines.
STDLIB. H describes some of the commonly used subroutines: conversion subroutines, search/Sort subroutines, and so on.
STRING. H describes some string operations and memory manipulation functions.
Sys\stat. H defines some of the symbolic constants that are used when opening and creating files.
Sys\types. H describes the Ftime function and the TIMEB structure.
Sys\time. H defines the type of time Time[zz (Z] [ZZ)]t.
Time. H defines the structure of the time-conversion subroutine Asctime, localtime, and gmtime, the types used for CTime, Difftime, Gmtime, localtime, and Stime, and provides prototypes of these functions.
VALUE. H defines some important constants, including those that depend on machine hardware and some constants that are described for compatibility with Unix System V, including the range of floating-point and double-precision values.

C how to read data from a comma-separated file in a language

To have commas, just add commas,
2,1,34,2,3,
1,400,5,
3,5,6,7,
Read:
for (j=0;j<nr;j++)
for (i=0;i<nc;i++)
FSCANF (Fin, "%d,", a[j][i]);
-----------------------------
If there is no comma at the end of the line, the number of data per row should be equal:
2,1,34,2
3,1,400,5
for (j=0;j<nr;j++) {
for (i=0;i<nc-1;i++) fscanf (Fin, "%d,", a[j][i]);
FSCANF (Fin, "%d,", a[j][nc-1]);
}
-----------------------------
Random with comma, random president
2,1,34,2,3
1,400,5
3,5,6,7
Read in the Fgets, calculate the president, by the character loop to find the comma, and the blank in place of the comma, and then read the data with SSCANF
----------------------------

Don't know the total number. One is to open a large array.

The second is pre-reading, number of numbers, open array,
Rewind (FIN);
and enter it from the beginning.


Common basic parameter comparison:

%d: Read in a decimal integer.

%i: Read in decimal, octal, hexadecimal integer, similar to%d, but at compile time by the data pre-set to differentiate the system, such as adding "0x" is hexadecimal, adding "0" is the octal. For example, the string "031" will be counted as 31 when using%d, but will count as 25 when using%i.

%u: Read in an unsigned decimal integer.

%f%f%g%g: Used to enter real numbers, which can be entered in decimal or exponential form.

%x%x: Read in hexadecimal integer.

%o: Reads in an octal integer.

%s: Read in a string and end with a space.

%c: Read in a character. Cannot read null value. Spaces can be read into.

  Additional Format Description character Table Modifier Description

l/l length modifier Enter "Long" data

H-Length modifier input "short" data

Turn from

Summary of Functions Fgets and fputs, Fread and Fwrite, fscanf, and fprintf usage (RPM)

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.