Many times we need to write data to the file when it is very disturbing, because the format of seven or eight slots, the readability is too poor,
So we think that there is no function can be formatted from the file input and output, there is really. Below I will explain
The power of fscanf and fprintf.
1, FSCANF (can be formatted from a file stream to read the data, encountered a space or return to stop)
Prototype: int fscanf(FILE *stream, const char *format, ...); fscanf (file stream pointers, format strings, output table columns);
Parameters:
File *stream: Stream pointer
const char *format, ... : The format of the string
Example:
FSCANF (FP, "%s%s%d", new1->number,new1->staddress,&new1->price); (in this case the data is entered into a file with a space in the middle of each data)
or write:
FSCANF (FP, "%s,%s,%d", New1->number,new1->staddress,&new1->price); (in this case, when the data is entered into a file, there will be a ', ' in the middle of each data)
2, fprintf (can be formatted to write data from a file stream)
Prototype: int fprintf(FILE *stream, const char *format, ...); fprintf (file stream pointers, format strings, output table columns);
Parameters:
A, file *stream: Stream pointer
b, const char *format, ... : The format of the string
Example:
fprintf (FP, "%s%s%d\n", New->number,new->staddress,new->price); Ditto
or write:
fprintf (FP, "%s,%s,%d\n", New->number,new->staddress,new->price); Ditto
Here's the code:
#include <stdio.h>#include<stdlib.h>#include<errno.h>#include<string.h>#defineLENGTH 100//the size of the arraytypedefstruct { CharNumber[length]; CharStaddress[length]; intPrice ;}*Node,node;intMainintargcChar*argv[]) {FILE*FP; FP= fopen ("Test.txt","A +");//Open the file as read-write permission (created if the file does not exist) if(fp = =NULL) {Perror ("fopen"); Exit (1); } nodeNew, New1;//new is used to hold the data written to the file, New1 to hold the data read from the file//allocating space for two struct pointers New= (node)malloc(sizeof(Node)); New1= (node)malloc(sizeof(Node)); //ClearMemsetNew,0,sizeof(node)); memset (New1,0,sizeof(node)); strcpy (New->number,"20170816"); strcpy (New->staddress,"Nanning"); New->price = -; fprintf (FP,"%s%s%d\n",New->number,New->staddress,New->price);//formatting writes data to a file
fseek (FP,0, Seek_set);//The file pointer is reset because the file stream pointer is positioned at the end of the file when the data is written to the file, so you need to relocate to the file headerfscanf (FP,"%s%s%d", New1->number,new1->staddress,&new1->price);//format read data from a fileprintf"%s%s%d\n",new1->number,new1->staddress,new1->Price ); //release two struct pointers Free(New); Free(New1); Fclose (FP); //Close File return 0;}
This is the result of my running on Ubuntu:
On-Screen output:
Open the contents of the Test.txt file:
FSCANF and fprintf in C language