如何在mfc中将数据写入同一文件? [英] How to write data into same file in mfc?

查看:164
本文介绍了如何在mfc中将数据写入同一文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Hai,

我是MFC.i的新手已完成工作线程。

一个线程通过创建一个.txt文件打印自然数字,我的意图是打开相同的文件和打印偶数。

能够通过在新线程中创建新的.txt文件来打印不同的文件。

但我需要相同的文件(这是由第一个线程创建)打开并打印偶数。

请帮帮我。

Hai,
am new to MFC.i have done worker thread.
one thread prints the natural numbers by creating one .txt file and my intention is to open the same file and print even numbers .
am able to print in different files by creating new .txt file in new thread.
but i need the same file(which is created by first thread) to be opened and prints even numbers.
please help me out.

推荐答案

在每个帖子中,无论何时你想要访问该文件:

In each thread, whenever you want access to the file:


  1. 在使用Windows API访问文件之前,创建一个命名的互斥锁(为其提供文件的完整路径)
  2. 使用C ++标准IO,打开文件。
  3. 使用C ++标准IO,写入文件。
  4. 使用C ++标准IO,关闭文件。
  5. 释放(不破坏)互斥锁



这是最基本的线程模式 - 锁定。它有严重的缺点(性能明智),因为线程被锁定等待互斥锁,所以实际上你的程序不再是多线程的。



另一种模式:



  • 创建一个线程,其唯一目的是管理对文件的访问。
  • 创建一个队列命令(你可以使用STL std :: queue);这个队列应该是自锁的。
  • 每当客户想要写一些文件时,在队列中添加一个'please write'命令。
  • 让你的文件访问pop命令从队列中逐个执行它们。
  • 每当客户端想要从文件中读取内容时,请向队列中添加读取命令。
  • 读取命令应该包含一个回调(通常指向接口的指针),当从队列中弹出'read'命令并执行时,执行该命令。

  • This is the most basic threading pattern - locking. It has serious disadvantages (performance wise), since threads are locked waiting for the mutex, so in fact your program is no longer multithreaded.

    Another pattern:


    • Create a thread whose only purpose will be managing access to the file.
    • Create a queue of commands (you may use the STL std::queue); this queue should be self-locking.
    • Whenever a client wants to write someting to the file, add a 'please write' command to the queue.
    • Have your file access pop commands from the queue, and execute them one by one.
    • Whenever a client wants to read something from the file, add a 'read' command to the queue.
    • The 'read' command should include a callback (pointer to interface, usually) to execute when the 'read' command is popped from the queue and executed.

    • 这篇关于如何在mfc中将数据写入同一文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆