1. Concept and role
Fwrite is a C-language function that points to a file that writes a block of data to a
fprintf is a format write-library function in C/s + + that is formatted to output to a stream/file; The prototype is an int fprintf (file *stream, const char *format, [argument] ...), fprintf () The function sends information (parameters) to the file specified by stream (stream) according to the specified format (format).
2. Usage
2.1 fwrite function
Example one:
/* fwrite example:write buffer */#include "stdafx.h" #include <stdio.h>int main (int argc, char* argv[]) { FILE * PFile; Char buffer[] = {' x ', ' y ', ' z '}; PFile = fopen ("D://myfile.txt", "WB"); fwrite (buffer, sizeof (char), sizeof (buffer), pFile); Fclose (pFile); return 0; }
Open Yes:
Example two:
/* fwrite example:write buffer */#include "stdafx.h" #include <stdio.h>int main (int argc, char* argv[]) { FILE * PFile; int buffer[] = {64,66,78}; PFile = fopen ("D://myfile.txt", "WB"); fwrite (buffer, sizeof (int), sizeof (buffer), pFile); Fclose (pFile); return 0; }
After executing the generated file, open Yes:
So, the problem is, why the example of the generated file is not garbled, the opening of example two garbled it? Please look at the difference
2.2 fprintf function
Example three:
/* fprintf Example */#include "stdafx.h" #include <stdio.h>int main (int argc, char* argv[]) { FILE * pFile; int N char name [+];p file = fopen ("D://myfile1.txt", "w"); for (n=0; n<3; n++) { puts ("Please, enter a name:"); Gets (name); fprintf (PFile, "Name%d [%-10.10s]\n", n,name); } fclose (pFile); return 0; }
Open the generated file is:
Example four:
If you modify the above code slightly, change it to Fwrite,
/* fprintf Example */#include "stdafx.h" #include <stdio.h>int main (int argc, char* argv[]) { FILE * pFile; int N char name [+];p file = fopen ("D://myfile.txt", "w"); for (n=0; n<3; n++) { puts ("Please, enter a name:"); Gets (name); fprintf (PFile, "Name%d [%-10.10s]\n", n,name); Fwrite (name, sizeof (char), sizeof (name), pFile);//Modify here} fclose (pFile); return 0; }
File Open is:
3. Differences
Problem One: Example one and example two, why one is readable, one is garbled?
A: write to the file with Fwrite if it can be expressed as a character, then it will be displayed as a character, if not shown, then write binary content (so-called garbled)
Question two: Example three and is four, why a readable, one is garbled?
A:fprintf writes the characters after the numbers are converted to ASCII code.
Open with Notepad to see, fwrite write Open is garbled, fprintf write is a readable character
In fact, these four sample generated files with fopen are readable, four files are not wrong
In short: If you want to make the generated files themselves can be understood, then choose fprintf, if you want to see, then use Fwrite, the two are written in different ways, the resulting file is computer-readable
Fwrite, the role and difference of fprintf