Application Example of the formatted read/write function (fscanf fprintf)

Source: Internet
Author: User

The fscanf and fprintf functions are similar to those of scanf and printf, both of which are 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 (FP, "% d % s", & num, STR );

Fprintf (FP, "% d % C", num, CH); // FP is the file pointer

Example:

Input five student data on the keyboard, write a file, and read the data of the five students on the screen.

# Include <stdio. h> struct stud {char name [10]; int num;} SW [5], Sr [5], * PW, * PR; // define an int main () {file * FP; int I; If (FP = fopen ("D: \ abc.txt ", "WB +") = NULL) // open the file {printf ("cannot open a file! ");} PW = Sw; // the pointer PW points to the array SW Pr = Sr; // the pointer PR points to the array Sr printf (" input data \ n "); printf ("name num \ n"); for (I = 0; I <5; I ++) scanf ("% S % d", SW [I]. name, & SW [I]. num); for (I = 0; I <5; I ++, PW ++) // read data into the file. Note that the point of PW changes to fprintf (FP, "% S % d \ n", PW-> name, PW-> num); rewind (FP); // move the internal pointer of the file to the file header for (I = 0; I <5; I ++, PR ++) fscanf (FP, "% S % d \ n", pr-> name, & pr-> num ); // read the information from the file into the struct printf ("\ nname num \ n"); for (I = 0; I <5; I ++) printf ("% S % 5d \ n", Sr [I]. name, Sr [I]. num); // read the information from the struct fclose (FP); // close the file 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.