LoginSignup
1
6

More than 3 years have passed since last update.

C/C++とC#のファイル共有モード

Last updated at Posted at 2019-10-29

ずっとC/C++を使ってて、このごろC#も使っているのですが、C/C++とC#でファイルのオープンした後の挙動ががなんか違うぞ、という事に気づきました。
C/C++では他のアプリケーションで使用中のファイルを普通に開くことが出来たのに、C#ではオープン時エラーになります。
コード書いて試してみたら、C/C++とC#でデフォルトのファイル共有モードに相違がありました。なんてこったい(・o・)

環境はWindows/VisualStudioです。

試したコード

以下はC/C++/C#でテキストファイルに追加書き込みする簡単なコードです。
エラーは省略しています。

C
#include <stdio.h>

void write_c(const char* fname)
{
    FILE *fp;
    fopen_s(&fp, fname, "a+");
    fprintf(fp, "this is c file.\n");
    fclose(fp);
}
C++
#include <fstream>

void write_cpp(const char* fname)
{
    std::ofstream ofs(fname, std::ios::app);
    ofs << "this is cpp stream" << std::endl;
}

CとC++では使用中ファイルのオープンに成功して、書き込みも出来ます。

C#
static void write_sc(string fileName)
{
    using (StreamWriter sw = new StreamWriter(fileName, true))
    {
        sw.WriteLine("this is cs");
    }
}

C#では他のアプリケーションで使用しているファイルをオープンすると例外が発生します。

C#で共有モードを設定して、オープン時のエラーを回避する

C#
static void write(string fileName)
{
    using (FileStream fs = new FileStream(fileName, FileMode.Append, FileAccess.Write, FileShare.Write))
    using (StreamWriter sw = new StreamWriter(fs))
    {
        sw.WriteLine("this is cs");
    }
}

FileStreamコンストラクタの最後のパラメータのFileShare.Writeで書き込み共有を設定しています。これでC/C++と同様に他のアプリケーションで使用しているファイルもエラーなくオープンできます。

1
6
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
6