1. Pure C implementation:
FILE *fp;if ((fp = fopen("example.txt", "rb")) == NULL){exit(0);}fseek(fp, 0, SEEK_END);int fileLen = ftell(fp);char *tmp = (char *) malloc(sizeof(char) * fileLen);fseek(fp, 0, SEEK_SET);fread(tmp, fileLen, sizeof(char), fp);fclose(fp);for(int i = 0; i < fileLen; ++i){printf("%d ", tmp[i]);}printf("\n");if ((fp = fopen("example.txt", "wb")) == NULL){exit(0);}rewind(fp);fwrite(tmp, fileLen, sizeof(char), fp);fclose(fp);free(tmp);
2. Use cfile (MFC base class)
The header file to be included in cfile is afx. h.
The function prototype for opening a file is as follows:
If (! (FP. Open (lpctstr) m_strsendfilepathname, cfile: moderead )))
There are multiple modes, commonly used as follows:
Moderead
Modewrite
Modereadwrite
Modecreate
There are two file types:
Typebinary
Typetext
You must use typebinary to read and write non-text files.
Function prototype for reading data:
Virtual uint read (void * lpbuf, uint ncount );
Code:
// Read the file cfile FP; If (! (FP. open (lpctstr) m_strsendfilepathname, cfile: moderead) {return;} FP. seektoend (); unsignedint fplength = FP. getlength (); char * TMP = new char [fplength]; FP. seektobegin (); // This sentence is indispensable if (FP. read (TMP, fplength) <1) {FP. close (); return;} // create a file and write it to If (! (FP. open (lpctstr) m_strsendfilepathname, cfile: modecreate | cfile: modewrite | cfile: typebinary) {return;} FP. seektobegin (); FP. write (TMP, fplength); FP. close;
The following method is provided:
# Include <stdio. h> # include <string. h> # define maxlen 10240 // read the file filename content to the Dest array, which can read a maximum of maxlen bytes // The number of bytes of the file returned successfully, -1 int read_file (const char * filename, char * DEST, int maxlen) {file * file; int POs, temp, I; // open the file = fopen (filename, "R"); If (null = file) {fprintf (stderr, "Open % s error \ n", filename ); return-1;} Pos = 0; // read the contents of the file cyclically for (I = 0; I <MAXLEN-1; I ++) {temp = fgetc (File); If ( EOF = temp) break; Dest [POS ++] = temp;} // close the file fclose (File); // Add 0 Dest [POS] = 0 at the end of the array; return Pos;} int main (INT argc, char ** argv) {If (argc! = 2) {fprintf (stderr, "using :. /read <FILENAME> \ n "); Return-1;} Char buffer [maxlen]; int Len = read_file (argv [1], buffer, maxlen ); // output file content printf ("Len: % d \ ncontent: \ n % s \ n", Len, buffer); Return 0 ;}