fscanf function usage and precautions

Source: Internet
Author: User

/*FSCANF.C:This program writes formatted data to afile.It then uses fscanf to read the various databackfromthefile.*/ #include <stdio.h> FILE *stream; int main( void ) { long l; float fp; char s[81]; char c; stream= fopen ( "fscanf.out" , "w+" ); if (stream==NULL) printf ( "The file fscanf.out was not opened\n" ); else { fprintf (stream, "%s%ld%f%c" , "a-string" , 65000,3.14159, ‘x‘ ); /*Set pointer to beginning of file:*/ fseek (stream,0L,SEEK_SET); /*Readdatabackfromfile:*/ fscanf (stream, "%s" ,s); fscanf (stream, "%ld" ,&l); fscanf (stream, "%f" ,&fp); fscanf (stream, "%c" ,&c); /*Output data read:*/ printf ( "%s\n" ,s); printf ( "%ld\n" ,l); printf ( "%f\n" ,fp); printf ( "%c\n" ,c); fclose (stream); } }

Precautions:

FSCANF (FILE * stream, Constchar*format, [argument ...]);

If argument is char* str
STR is a pointer to an array of strings used to copy the read string
So, it can be char s[128]
It can also be char* s = (char *) malloc (128)

But it can not be char* s; s does not point to a valid memory space




FILE *fp; char a[10]; int b; double c; fscanf (fp, "%s%d%lf" ,a,&b,&c)




printf ("%g", 4.5);//4.5
printf ("%f", 4.5);//4.500000
printf ("%e", 400.5);//4.5e+2

fscanf function usage and precautions

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.