现在的位置: 首页 > 综合 > 正文

把一个文件到追加另外一个文件上(vc版)

2014年02月28日 ⁄ 综合 ⁄ 共 2221字 ⁄ 字号 评论关闭

 

下面这个例子演示了如何打开和关闭文件,如何读取和保存文件,如何锁定和解锁文件。这个程序的功能是把一个文件上的数据追加到另外一个文件结尾位置。这个程序打开文件并且把文件中的数据追加到只允许当前程序执行保存的文件中,但是允许其它进程打开并且读取正在被当前进程追加的文件。为了使读者对文件有一个深入的理解,我们在写的过程中调用了文件锁定功能。

 

这个程序使用CreateFile打开两个文件。打开One.txt是为了读取其中的数据,打开Two.txt文件是为了执行追加,同时Two.txt文件还支持共享读功能,也就是允许其它进程读取这个文件。程序先读取第一个文件中内容再把读取到的内容追加到第二个文件末尾,调用ReadFileWriteFile函数实现读取和保存4K的内容。在写第二个文件之前,程序先调用SetFilePointer函数移到文件末尾,同时使用LockFile锁定要执行写操作的区域,执行锁定功能是为了防止在写的过程中其它拥有当前句柄副本的线程或进程存取这块区域。执行完一次写的功能,我们就会调用UnlockFile对这块区域进行解锁。在执行完锁定功能之后我们就没有必须再调用SetFilePointer函数,因为只可能有一个进程能够执行写的操作。

//这个程序的工程,创建,编译,为:

vc6.0-》file-》new-》win32 console application-》an application that supports mfc-> 把如下代码copy到 // TODO: code your application's behavior here.

代码:

   HANDLE hFile;
  HANDLE hAppend;
  DWORD  dwBytesRead, dwBytesWritten, dwPos;
  BYTE   buff[4096];
  // Open the existing file.
  hFile = CreateFile(TEXT("c://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 attr. template
  if (hFile == INVALID_HANDLE_VALUE)
  {
   printf("Could not open One.txt.");
   return 1;
  }
  
  // Open the existing file, or if the file does not exist,
  // create a new file.
  hAppend = CreateFile(TEXT("c://two.txt"), // open Two.txt
   GENERIC_WRITE,            // open for writing
   FILE_SHARE_READ,          // allow multiple readers
   NULL,                     // no security
   OPEN_ALWAYS,              // open or create
   FILE_ATTRIBUTE_NORMAL,    // normal file
   NULL);                    // no attr. template
  
  if (hAppend == INVALID_HANDLE_VALUE)
  {
   printf("Could not open Two.txt.");
   return 1;
  }
  // Append the first file to the end of the second file.
  // Lock the second file to prevent another process from
  // accessing it while writing to it. Unlock the
  // file when writing is finished.
  do
  {
   if (ReadFile(hFile, buff, sizeof(buff), &dwBytesRead, NULL))
   {
    dwPos = SetFilePointer(hAppend, 0, NULL, FILE_END);
    LockFile(hAppend, dwPos, 0, dwBytesRead, 0);
    WriteFile(hAppend, buff, dwBytesRead, &dwBytesWritten, NULL);
    UnlockFile(hAppend, dwPos, 0, dwBytesRead, 0);
   }
  } while (dwBytesRead == sizeof(buff));
  // Close both files.
  CloseHandle(hFile);
        CloseHandle(hAppend);
  
  cout<<"追加文件成功!"<<"\n";

抱歉!评论已关闭.