C++ fout.open 如何改成共享模式

**软件打开后CSV文件无法编辑

如何把这段代码改成共享模式,即使软件打开后其他程序也可以打开**


void   fastcall TForm1::FormCreate(TObject *Sender)
{
        String FileName;
        char* path;                                                             // 要创建文件的路径
        FileName = ".\\LOG\\" + DateToStr(Date()) + ".csv";

        
       fout.open(path ,ios::app);path = FileName.c_str();
        //fout( path ,ios::app);                                         //尝试打开文件,如果不存在则创建文件并增加稳在内容到最后一行
        if ( !fout )                                                            //如果失败
        {
            ForceDirectories(".\\LOG");                                         //那么在当前目录下强制创建LOG文件夹
        }
        bFirstRun = true;
        Form1->Width = 624;
}
//---------------------------------------------------------------------------

void    fastcall TForm1::FormClose(TObject *Sender, TCloseAction &Action)
{
        fout.close();                                                           // 执行完操作后关闭文件句柄
}

img


是不是文件属性设置成只读了?修改一下试试?

open这个函数是不支持共享的,所以改用这个函数的带共享模式参数的版本:_fsopen。
_fsopen
以共享的方式打开文件或者流
 FILE *_fsopen( const char *filename, const char *mode, int shflag );  
filename  Name of the file to open.  //需要打开的文件名
mode   Type of access permitted.  //可以访问的类型
shflag   Type of sharing allowed.  //共享访问类型
可用参数:
 _SH_COMPAT   Sets Compatibility mode for 16-bit applications. //以兼容模式打开16位程序
 _SH_DENYNO   Permits read and write access.  //充许读和写 以此模式打开类似fopen
 _SH_DENYRD   Denies read access to the file.  //拒绝读
 _SH_DENYRW   Denies read and write access to the file.   //拒绝读和写
 _SH_DENYWR   Denies write access to the file //拒绝写

有帮助的话采纳一下哦

代码给你稍微修改了下,里边有注释,如下

FILE* m_f1 = NULL; //声明成员指针变量,根据实际情况,放到头文件里边

    void   fastcall TForm1::FormCreate(TObject * Sender)
    {
        String FileName;
        char* path;                                                             // 要创建文件的路径
        FileName = ".\\LOG\\" + DateToStr(Date()) + ".csv";


        //fout.open(path, ios::app); 
        path = FileName.c_str();
        m_f1 = _fsopen(path, "wb+", _SH_DENYNO);//以共享模式打开文件,只支持英文路径
        //fout( path ,ios::app);                                         //尝试打开文件,如果不存在则创建文件并增加稳在内容到最后一行
        //if (!fout)                                                            //如果失败
        if(!m_f1)
        {
            ForceDirectories(".\\LOG");                                         //那么在当前目录下强制创建LOG文件夹
        }
        bFirstRun = true;
        Form1->Width = 624;
    }
    //---------------------------------------------------------------------------

    void    fastcall TForm1::FormClose(TObject * Sender, TCloseAction & Action)
    {
        //fout.close();                                                           // 执行完操作后关闭文件句柄

        fclose(m_f1); // 执行完操作后关闭文件句柄
    }

fout以可写方式打开一个文件后,其他软件只能以可读方式打开该文件,不能编辑该文件