(Windows)中同时打开相同的文件 [英] (Windows) Open the same file simultaneously

查看:241
本文介绍了(Windows)中同时打开相同的文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图打开一个文件进行读写同时进行,在Windows中。
我有一个计划,写(每1秒)的文件,一个从中读取。在Unix它的工作原理prefectly,但它不工作在Windows(我不能打开一个已经打开的文件)。
我打开用FOPEN文件()。

我该如何解决这个问题呢?

EDIT2:

查看 _fsopen 它使用 FILE * ,并设置相应的份额标志。

编辑:

首先,一些code:这是我用来打开文件

  FILE * F = NULL;
        INT解析度= fopen_s(安培; F,C:\\\\ \\\\温度FILE1.TXT,W);
        如果(RES!= 0)回报;        而(真){
            睡眠(1000);
            fprintf_s(F,一些数据);
        }
        FCLOSE(F);

读取在其他应用程序了,但它确实的fscanf 代替。

固定code:

 字符D [] =数据;
手柄H =的CreateFile(C:\\\\ \\\\温度f.txt,GENERIC_READ | GENERIC_WRITE,
    FILE_SHARE_WRITE | FILE_SHARE_READ,NULL,CREATE_ALWAYS,/ * FILE_ATTRIBUTE_NORMAL * / FILE_FLAG_WRITE_THROUGH,NULL);如果(H == INVALID_HANDLE_VALUE)返回0;DWORD bytesW;
而(真){
    睡眠(100);
        WriteFile的(H,D,strlen的(D),放大器; bytesW,NULL);
}CloseHandle的(H);
返回0;


解决方案

Windows和Linux都打开一个文件,其中的fopen 默认使用。的默认方式

在Windows中,这意味着阻断(只有一个进程可以打开一次的文件)。

在Linux中,这意味着无阻塞。

的fopen 是一个高层次的API。要选择自己的文件分块政策,适用于Windows,你应该使用的打开文件从WinAPI的。特别是,有一个看 OF_SHARE _ * 标记。

I am trying to open a file for writing and reading simultaneously, in windows. I have one program which writes (every one second) to the file and one that reads from it. In unix it works prefectly but it doesn't work in windows (I can't open an already opened file). I open the file with fopen().

How can I solve this problem?

EDIT2:

check out _fsopen it uses FILE *, and set the share flag accordingly.

EDIT:

First of all, some code: this is how I used to open the file

   FILE* f = NULL;
        int res = fopen_s(&f, "c:\\temp\\File1.txt", "w");
        if (res != 0) return;

        while (true) {
            Sleep(1000);
            fprintf_s(f , "Some data");
        }
        fclose(f); 

The read was in other applicaiton, but it did fscanf instead.

The fixed code:

char d[] = "data";


HANDLE h = CreateFile("c:\\temp\\f.txt", GENERIC_READ | GENERIC_WRITE,
    FILE_SHARE_WRITE | FILE_SHARE_READ, NULL, CREATE_ALWAYS, /*FILE_ATTRIBUTE_NORMAL*/ FILE_FLAG_WRITE_THROUGH, NULL);

if (h == INVALID_HANDLE_VALUE) return 0;

DWORD bytesW;
while(true) {
    Sleep(100);
        WriteFile(h, d, strlen(d), &bytesW, NULL);
}

CloseHandle(h);
return 0; 

解决方案

Both Windows and Linux have a default way of opening a file, which fopen uses by default.

In Windows, that means blocking (only one process can open a file at a time).

In Linux, it means non-blocking.

fopen is a high-level API. To choose yourself the blocking policy on the file, for Windows you should use OpenFile from WinAPI. In particular, have a look at the OF_SHARE_* flags.

这篇关于(Windows)中同时打开相同的文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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