分类: C/C++
2008-08-21 10:28:39
The following code example shows how to append one file to the end of another file. In the example, =CreateFile opens two text (.txt) files: One.txt for reading and Two.txt for writing. Then, the and functions append the contents of One.txt to the end of Two.txt by reading and writing 4-KB blocks.
void AppendExample (void) { HANDLE hFile, hAppend; DWORD dwBytesRead, dwBytesWritten, dwPos; char buff[4096]; TCHAR szMsg[1000]; // Open the existing file. hFile = CreateFile (TEXT("\\ONE.TXT"), // Open One.txt GENERIC_READ, // Open for reading 0, // Do not share NULL, // No security OPEN_EXISTING, // Existing file only FILE_ATTRIBUTE_NORMAL, // Normal file NULL); // No template file if (hFile == INVALID_HANDLE_VALUE) { // Your error-handling code goes here. wsprintf (szMsg, TEXT("Could not open ONE.TXT")); return; } // Open the existing file, or, if the file does not exist, // create a new file. hAppend = CreateFile (TEXT("\\TWO.TXT"), // Open Two.txt. GENERIC_WRITE, // Open for writing 0, // Do not share NULL, // No security OPEN_ALWAYS, // Open or create FILE_ATTRIBUTE_NORMAL, // Normal file NULL); // No template file if (hAppend == INVALID_HANDLE_VALUE) { wsprintf (szMsg, TEXT("Could not open TWO.TXT")); CloseHandle (hFile); // Close the first file. return; } // Append the first file to the end of the second file. dwPos = SetFilePointer (hAppend, 0, NULL, FILE_END); do { if (ReadFile (hFile, buff, 4096, &dwBytesRead, NULL)) { WriteFile (hAppend, buff, dwBytesRead, &dwBytesWritten, NULL); } } while (dwBytesRead == 4096); // Close both files. CloseHandle (hFile); CloseHandle (hAppend); return; } // End of AppendExample code