C ++ file writing example, file writing example
#include <iostream>#include <sstream>#include <fstream>>using namespace std;/* run this program using the console pauser or add your own getch, system("pause") or input loop */int main(int argc, char** argv) { ofstream myfile; myfile.open("example.txt"); myfile <<"write test"; myfile.close();return 0;}
C language file read/write instance
# Include "stdio. h"
# Include "stdlib. h"
Int main (void ){
FILE * p;
Int B [10], I;
P = fopen ("E: \ Csource \ read \ Debug \ a.txt", "r ");
If (p = NULL ){
Fprintf (stderr, "Error on open file a.txt \ n ");
Exit (EXIT_FAILURE );
}
For (I = 0; I <10; fscanf (p, "% d", & B [I ++]);
Fclose (p );
P = fopen ("E: \ Csource \ read \ Debug \ B .txt", "w ");
If (p = NULL ){
Fprintf (stderr, "Error on open file B .txt \ n ");
Exit (EXIT_FAILURE );
}
For (I = 9; I> = 0; fprintf (p, "% d", B [I --]);
Fclose (p );
Return 0;
}
How to write the C header file !! I 'd like to give you an example. Thank you very much.
A simple method: first write the complete program, then extract some of it, store it in your own header file, and write # include...
For example, the complete program (calculate the average value ):
# Include <stdio. h>
Double mean (double * y, int N ){
Int I;
Double s = 0.0;
For (I = 0; I <N; I ++) s = s + y [I];
S = s/(double) N;
Return s;
}
Void main ()
{
Double x [10] = {1, 2, 4, 5, 6, 7, 8, 9, 10 };
Printf ("mean = % lf \ n", mean (x, 10 ));
}
----------------------------------------------
Save the extracted part to a_x.h:
Double mean (double * y, int N ){
Int I;
Double s = 0.0;
For (I = 0; I <N; I ++) s = s + y [I];
S = s/(double) N;
Return s;
}
--------------------------------
Program changes:
# Include <stdio. h>
# Include "a_x.h"
Void main ()
{
Double x [10] = {1, 2, 4, 5, 6, 7, 8, 9, 10 };
Printf ("mean = % lf \ n", mean (x, 10 ));
}
========================================================== =====
You can also select a random part, for example, extract (also called a_x.h ):
Double mean (double * y, int N ){
Int I;
Double s = 0.0;
For (I = 0; I <N; I ++) s = s + y [I];
S = s/(double) N;
Return s;
}
Void main ()
{
------------------------
Program changes:
# Include <stdio. h>
# Include "a_x.h"
Double x [10] = {1, 2, 4, 5, 6, 7, 8, 9, 10 };
Printf ("mean = % lf \ n", mean (x, 10 ));
}
====================================
In terms of syntax and function, both methods can be used. But the first method is better-the program is readable and error-prone.
Generally, the header file contains the function prototype, global volume declaration, and function definition.