// C:\\a.txt に、aaa という名前でファイルストリームを作成し、読み込むサンプル
// NTFS フォーマットのドライブでのみ実行可能
#include <windows.h>
#include <tchar.h>
#include <io.h>
#include <fcntl.h>
#include <sys/stat.h>
// エントリポイント
int WINAPI _tWinMain ( HINSTANCE hThisInstance,
HINSTANCE,
_TCHAR *,
int )
{
const _TCHAR cszPath[] = _TEXT ( "C:\\a.txt" );
// C:\\a.txt がない場合は、作成
WIN32_FIND_DATA win32FindData;
memset ( &win32FindData, 0, sizeof ( WIN32_FIND_DATA ) );
HANDLE hFindFile;
hFindFile = FindFirstFile ( cszPath, &win32FindData );
if ( INVALID_HANDLE_VALUE == hFindFile )
{
// "C:\\a.txt" の中身は、"ABC"
int nHandle;
nHandle = _topen ( cszPath, _O_BINARY | _O_CREAT | _O_WRONLY, _S_IWRITE );
if ( -1 == nHandle )
{
MessageBox ( NULL,
_TEXT ( "open failed - C:\\a.txt" ),
_TEXT ( "Error" ),
MB_OK | MB_ICONSTOP );
return 0;
}
const _TCHAR cszABC[] = _TEXT ( "ABC" );
if ( -1 == _write ( nHandle, cszABC, lstrlen ( cszABC ) * sizeof ( _TCHAR ) ) )
{
_close ( nHandle );
MessageBox ( NULL,
_TEXT ( "write failed - C:\\a.txt" ),
_TEXT ( "Error" ),
MB_OK | MB_ICONSTOP );
return 0;
}
_close ( nHandle );
}
else
{
// 検索終了
FindClose ( hFindFile );
}
// "C:\\a.txt"に ファイルストリーム "aaa" を作成 ( 中身は、"DEFG" )
const _TCHAR cszPath2[] = _TEXT ( "C:\\a.txt:aaa" );
int nHandle;
nHandle = _topen ( cszPath2, _O_BINARY | _O_CREAT | _O_WRONLY, _S_IWRITE );
if ( -1 == nHandle )
{
MessageBox ( NULL,
_TEXT ( "open failed - C:\\a.txt:aaa" ),
_TEXT ( "Error" ),
MB_OK | MB_ICONSTOP );
return 0;
}
const _TCHAR cszDEF[] = _TEXT ( "DEFG" );
if ( -1 == _write ( nHandle, cszDEF, lstrlen ( cszDEF ) * sizeof ( _TCHAR ) ) )
{
_close ( nHandle );
MessageBox ( NULL,
_TEXT ( "write failed - C:\\a.txt:aaa" ),
_TEXT ( "Error" ),
MB_OK | MB_ICONSTOP );
return 0;
}
_close ( nHandle );
// 書き込んだ内容を閲覧
nHandle = _topen ( cszPath2, _O_BINARY | _O_RDONLY );
int nFileLength = _filelength ( nHandle );
_TCHAR *pszData = new _TCHAR[ nFileLength + 1 ];
memset ( pszData, 0, ( nFileLength + 1 ) * sizeof ( _TCHAR ) );
if ( -1 == _read ( nHandle, pszData, nFileLength ) )
{
delete[] pszData;
_close ( nHandle );
MessageBox ( NULL,
_TEXT ( "read failed - C:\\a.txt:aaa" ),
_TEXT ( "Error" ),
MB_OK | MB_ICONSTOP );
return 0;
}
_close ( nHandle );
MessageBox ( NULL,
pszData,
_TEXT ( "C:\\a.txt:aaa の内容は" ),
MB_OK );
delete[] pszData;
return 0;
}
|