C文件操作:
/* fopen example */ #include <stdio.h> int main () { FILE * pFile; pFile = fopen ("myfile.txt","w"); if (pFile!=NULL) { fputs ("fopen example",pFile); fclose (pFile); } return 0; }
/* fprintf example */ #include <stdio.h> int main () { FILE * pFile; int n; char name [100]; pFile = fopen ("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); } fclose (pFile); return 0; }
/* sprintf example */ #include <stdio.h> int main () { char buffer [50]; int n, a=5, b=3; n=sprintf (buffer, "%d plus %d is %d", a, b, a+b); printf ("[%s] is a %d char long string\n",buffer,n); return 0; }
/* sscanf example */ #include <stdio.h> int main () { char sentence []="Rudolph is 12 years old"; char str [20]; int i; sscanf (sentence,"%s %*s %d",str,&i); printf ("%s -> %d\n",str,i); return 0; }
C++文件操作:
// Copy a file #include <fstream> using namespace std; int main () { char * buffer; long size; ifstream infile ("test.txt",ifstream::binary); ofstream outfile ("new.txt",ofstream::binary); // get size of file infile.seekg(0,ifstream::end); size=infile.tellg(); infile.seekg(0); // allocate memory for file content buffer = new char [size]; // read content of infile infile.read (buffer,size); // write to outfile outfile.write (buffer,size); // release dynamically-allocated memory delete[] buffer; outfile.close(); infile.close(); return 0; }
// read a file into memory #include <iostream> #include <fstream> using namespace std; int main () { int length; char * buffer; ifstream is; is.open ("test.txt", ios::binary ); // get length of file: is.seekg (0, ios::end); length = is.tellg(); is.seekg (0, ios::beg); // allocate memory: buffer = new char [length]; // read data as a block: is.read (buffer,length); is.close(); cout.write (buffer,length); delete[] buffer; return 0; }