vc 直接写物理磁盘,writefile 失败 错误返回5 拒绝访问

高小阳 2014-03-13 05:14:05
如题,求解决问题,createfile("\\\\.\\PhysicalDrive2", GENERIC_READ | GENERIC_WRITE,
FILE_SHARE_READ | FILE_SHARE_WRITE,
NULL,
OPEN_EXISTING,
0,
NULL);
...全文
2117 25 打赏 收藏 转发到动态 举报
写回复
用AI写文章
25 条回复
切换为时间正序
请发表友善的回复…
发表回复
dongguaWDY 2015-04-18
  • 打赏
  • 举报
回复
怎么解决啊?亲
怎嘛回事 2014-12-30
  • 打赏
  • 举报
回复
引用 22 楼 doctor_yang 的回复:
首先把 一个物理驱动器下的 所有逻辑驱动器 (盘符) 打开 (得到逻辑驱动器句柄) 通过DeviceIoControl (FSCTL_LOCK_VOLUME. )锁驱动器, 然后creatfile 打开物理驱动器 就可以读写了 , 最后别忘了FSCTL_UNLOCK_VOLUME 解锁
你这个是逻辑写入,楼主问的是物理写入。 对于大部分FAT32来说,物理地址=逻辑地址。但是也有部分U盘的是不同的。 FAT32格式被windows系统保护了,不允许直接写入物理地址,但是读是没问题的。
寒江雪语 2014-07-10
  • 打赏
  • 举报
回复
引用 22 楼 doctor_yang 的回复:
首先把 一个物理驱动器下的 所有逻辑驱动器 (盘符) 打开 (得到逻辑驱动器句柄) 通过DeviceIoControl (FSCTL_LOCK_VOLUME. )锁驱动器, 然后creatfile 打开物理驱动器 就可以读写了 , 最后别忘了FSCTL_UNLOCK_VOLUME 解锁
楼主,能不能求下win7下写扇区这点代码,最近也在写类似的程序,这个问题一直解决不了,先谢过了
高小阳 2014-05-14
  • 打赏
  • 举报
回复
首先把 一个物理驱动器下的 所有逻辑驱动器 (盘符) 打开 (得到逻辑驱动器句柄) 通过DeviceIoControl (FSCTL_LOCK_VOLUME. )锁驱动器, 然后creatfile 打开物理驱动器 就可以读写了 , 最后别忘了FSCTL_UNLOCK_VOLUME 解锁
David_359 2014-05-04
  • 打赏
  • 举报
回复
引用 18 楼 doctor_yang 的回复:
现在运行已经关闭UAC 并且管理员身份运行的
楼主 如何解决的?赐教一下呀。
David_359 2014-05-04
  • 打赏
  • 举报
回复
如何解决的呀亲?
高小阳 2014-03-24
  • 打赏
  • 举报
回复
已经解决,结贴了
高小阳 2014-03-17
  • 打赏
  • 举报
回复
现在运行已经关闭UAC 并且管理员身份运行的
赵4老师 2014-03-17
  • 打赏
  • 举报
回复
引用 16 楼 doctor_yang 的回复:
根据楼上的 我用了 如下参数 ,但还是解决不了 在Win7下 直接写物理磁盘问题啊 FSCTL_LOCK_VOLUME. FSCTL_DISMOUNT_VOLUME FSCTL_ALLOW_EXTENDED_DASD_IO
关闭UAC 以管理员身份运行
高小阳 2014-03-17
  • 打赏
  • 举报
回复
根据楼上的 我用了 如下参数 ,但还是解决不了 在Win7下 直接写物理磁盘问题啊 FSCTL_LOCK_VOLUME. FSCTL_DISMOUNT_VOLUME FSCTL_ALLOW_EXTENDED_DASD_IO
赵4老师 2014-03-14
  • 打赏
  • 举报
回复
//接上帖
DWORD
_cdecl
main(
    int argc,
    char *argv[],
    char *envp[]
    )
{
    char Drive[MAX_PATH];
    HANDLE hDrive, hDiskImage;
    DISK_GEOMETRY Geometry;
    UINT i;
    char c, *p;
    LPSTR DriveName;
    BOOL fUsage = TRUE;
    BOOL fShowGeometry = FALSE;
    BOOL fDiskImage = FALSE;
    BOOL SourceIsDrive;
    LPSTR Source, Destination, DiskImage;

    if ( argc > 1 ) {
        fUsage = FALSE;
        while (--argc > 0 ) {
            p = *++argv;
            if (*p == '/' || *p == '-') {
                while (c = *++p)
                switch (toupper( c )) {
                case '?':
                    fUsage = TRUE;
                    break;

                case 'C':
                    fDiskImage = TRUE;
                    argc--, argv++;
                    Source = *argv;
                    argc--, argv++;
                    Destination = *argv;
                    break;

                case 'G':
                    argc--, argv++;
                    if ( (DriveName = *argv ) && *DriveName &&
                         isalpha(*DriveName) )
                        fShowGeometry = TRUE;
                    else
                                                {
                        printf( "MFMT: Missing drive letter after -G\n" );
                                    DriveName = NULL;
                        fUsage = TRUE;
                        }
                            break;

                default:
                    printf("MFMT: Invalid switch - /%c\n", c );
                    fUsage = TRUE;
                    break;
                    }
                }
            }
        }

	if ( fUsage	) {
		printf("usage: MFMT switches \n" );
		printf("            [-?] display this message\n" );
		printf("            [-g drive] shows disk geometry\n" );
		printf("            [-c source destination] produce diskimage\n" );
		ExitProcess(1);
		}

	if ( fShowGeometry ) {
		sprintf(Drive,"\\\\.\\%s",DriveName);
		hDrive = CreateFile(
					Drive,
					GENERIC_READ | GENERIC_WRITE,
					FILE_SHARE_READ|FILE_SHARE_WRITE,
					NULL,
					OPEN_EXISTING,
					0,
					NULL
					);
		if ( hDrive	== INVALID_HANDLE_VALUE	) {
			printf("MFMT: Open %s failed %d\n",DriveName,GetLastError());
			ExitProcess(1);
			}

		if ( LockVolume(hDrive)	== FALSE ) {
			printf("MFMT:Locking volume %s failed %d\n", DriveName, GetLastError());
			ExitProcess(1);
			}

		if ( !GetDiskGeometry(hDrive,&Geometry)	) {
			printf("MFMT: GetDiskGeometry %s failed %d\n",DriveName,GetLastError());
			ExitProcess(1);
			}
		PrintGeometry(DriveName,&Geometry);

		if ( !GetSupportedGeometrys(hDrive)	) {
			printf("MFMT: GetSupportedGeometrys %s failed %d\n",DriveName,GetLastError());
			ExitProcess(1);
			}
		printf("\nDrive %s supports the following disk geometries\n",DriveName);

		for(i=0;i<SupportedGeometryCount;i++) {
			printf("\n");
			PrintGeometry(NULL,&SupportedGeometry[i]);
			}

		printf("\n");
		ExitProcess(0);
		}

	if ( fDiskImage	) {
		SourceIsDrive =	FALSE;
		if ( Source[strlen(Source)-1] == ':' ) {
			SourceIsDrive =	TRUE;
			sprintf(Drive,"\\\\.\\%s",Source);
			DriveName=Source;
			DiskImage =	Destination;
			}
		if ( Destination[strlen(Destination)-1]	== ':' ) {
			if ( SourceIsDrive ) {
				printf("MFMT: Source and Destination cannot both be drives\n");
				ExitProcess(1);
				}
			SourceIsDrive =	FALSE;
			sprintf(Drive,"\\\\.\\%s",Destination);
			DriveName=Destination;
			DiskImage =	Source;
			}
		else {
			if ( !SourceIsDrive	) {
				printf("MFMT: Either Source or Destination must be a drive\n");
				ExitProcess(1);
				}
			}

		//
		// Open	and	Lock the drive
		//

		hDrive = CreateFile(
					Drive,
					GENERIC_READ | GENERIC_WRITE,
					FILE_SHARE_READ|FILE_SHARE_WRITE,
					NULL,
					OPEN_EXISTING,
					0,
					NULL
					);
		if ( hDrive	== INVALID_HANDLE_VALUE	) {
			printf("MFMT: Open %s failed %d\n",DriveName,GetLastError());
			ExitProcess(1);
			}
		if ( LockVolume(hDrive)	== FALSE ) {
			printf("MFMT: LockVolume %s failed %d\n",DriveName,GetLastError());
			ExitProcess(1);
			}

		if ( !GetDiskGeometry(hDrive,&Geometry)	) {
			printf("MFMT: GetDiskGeometry %s failed %d\n",DriveName,GetLastError());
			ExitProcess(1);
			}

		if ( !GetSupportedGeometrys(hDrive)	) {
			printf("MFMT: GetSupportedGeometrys %s failed %d\n",DriveName,GetLastError());
			ExitProcess(1);
			}

		//
		// Open	the	disk image file
		//

		hDiskImage = CreateFile(
						DiskImage,
						GENERIC_READ | GENERIC_WRITE,
						0,
						NULL,
						SourceIsDrive ?	CREATE_ALWAYS :	OPEN_EXISTING,
						0,
						NULL
						);
		if ( hDiskImage	== INVALID_HANDLE_VALUE	) {
			printf("MFMT: Open %s failed %d\n",DiskImage,GetLastError());
			ExitProcess(1);
			}

		//
		// Now do the copy
		//
		{
			LPVOID IoBuffer;
			BOOL b;
			DWORD BytesRead, BytesWritten;
			DWORD FileSize;
			DWORD VirtBufSize;
			DWORD NumBufs;

			//
			// If we are copying from floppy to	file, just do the copy
			// Otherwise, we might have	to format the floppy first
			//

			if ( SourceIsDrive ) {

				//
				// Device reads	must be	sector aligned.	VirtualAlloc will
				// garuntee	alignment
				//

				NumBufs	= Geometry.Cylinders.LowPart;
				VirtBufSize	=  Geometry.TracksPerCylinder *
							   Geometry.SectorsPerTrack	*
							   Geometry.BytesPerSector;

				IoBuffer = VirtualAlloc(NULL,VirtBufSize,MEM_COMMIT,PAGE_READWRITE);

				if ( !IoBuffer ) {
					printf("MFMT: Buffer Allocation Failed\n");
					ExitProcess(1);
					}

				for	( ;NumBufs > 0;	NumBufs-- )
					{
					b =	ReadFile(hDrive,IoBuffer, VirtBufSize, &BytesRead, NULL);
					if (b && BytesRead){
						b =	WriteFile(hDiskImage,IoBuffer, BytesRead, &BytesWritten, NULL);
						if ( !b	|| ( BytesRead != BytesWritten ) ) {
							printf("MFMT: Fatal Write Error %d\n",GetLastError());
							ExitProcess(1);
							}
						}
					else {
						printf("MFMT: Fatal Read Error %d\n",GetLastError());
						ExitProcess(1);
						}
					}
				}
			else {

				//
				// Check to	see	if the image will fit on the floppy. If	it
				// will, then LowLevelFormat the floppy	and	press on
				//

				FileSize = GetFileSize(hDiskImage,NULL);

				b =	FALSE;
				for(i=0;i<SupportedGeometryCount;i++) {
					NumBufs	= SupportedGeometry[i].Cylinders.LowPart;
					VirtBufSize	=  SupportedGeometry[i].TracksPerCylinder *
								   SupportedGeometry[i].SectorsPerTrack	*
								   SupportedGeometry[i].BytesPerSector;
					if ( VirtBufSize*NumBufs >=	FileSize ) {

						IoBuffer = VirtualAlloc(NULL,VirtBufSize,MEM_COMMIT,PAGE_READWRITE);

						if ( !IoBuffer ) {
							printf("MFMT: Buffer Allocation Failed\n");
							ExitProcess(1);
							}

						//
						// Format the floppy
						//

						LowLevelFormat(hDrive,&SupportedGeometry[i]);

						for	( ;NumBufs > 0;	NumBufs-- )
							{
							b =	ReadFile(hDiskImage,IoBuffer, VirtBufSize, &BytesRead, NULL);
							if (b && BytesRead){
								b =	WriteFile(hDrive,IoBuffer, BytesRead, &BytesWritten, NULL);
								if ( !b	|| ( BytesRead != BytesWritten ) ) {
									printf("MFMT: Fatal Write Error %d\n",GetLastError());
									ExitProcess(1);
									}
								}
							else {
								printf("MFMT: Fatal Read Error %d\n",GetLastError());
								ExitProcess(1);
								}
							}
						b =	TRUE;
						break;
					}
					}

				if ( !b	) {
					printf("MFMT: FileSize %d is not supported on drive %s\n",FileSize,DriveName);
					ExitProcess(1);
					}
				}
		}

		//
		// Dismounting forces the filesystem to	re-evaluate	the	media id
		// and geometry. This is the same as popping the floppy	in and out
		// of the disk drive
		//

		DismountVolume(hDrive);
		UnlockVolume(hDrive);

		ExitProcess(0);
		}
	return (0);
}
赵4老师 2014-03-14
  • 打赏
  • 举报
回复
仅供参考:
#include <stdlib.h>
#include <stdio.h>
#include <windows.h>
#include <winioctl.h>
#include <string.h>
#include <ctype.h>
#include <memory.h>

DISK_GEOMETRY SupportedGeometry[20];
DWORD SupportedGeometryCount;

BOOL
GetDiskGeometry(
    HANDLE hDisk,
    PDISK_GEOMETRY lpGeometry
    )

{
    DWORD ReturnedByteCount;

    return DeviceIoControl(
                hDisk,
                IOCTL_DISK_GET_DRIVE_GEOMETRY,
                NULL,
                0,
                lpGeometry,
                sizeof(*lpGeometry),
                &ReturnedByteCount,
                NULL
                );
}

DWORD
GetSupportedGeometrys(
    HANDLE hDisk
    )
{
    DWORD ReturnedByteCount;
    BOOL b;
    DWORD NumberSupported;

    b = DeviceIoControl(
                hDisk,
                IOCTL_DISK_GET_MEDIA_TYPES,
                NULL,
                0,
                SupportedGeometry,
                sizeof(SupportedGeometry),
                &ReturnedByteCount,
                NULL
                );
    if ( b ) {
        NumberSupported = ReturnedByteCount / sizeof(DISK_GEOMETRY);
        }
    else {
        NumberSupported = 0;
        }
    SupportedGeometryCount = NumberSupported;

    return NumberSupported;
}

VOID
PrintGeometry(
    LPSTR lpDriveName,
    PDISK_GEOMETRY lpGeometry
    )
{
    LPSTR MediaType;

    if (lpDriveName) {
        printf("Geometry for Drive %s\n",lpDriveName);
        }

    switch ( lpGeometry->MediaType ) {
        case F5_1Pt2_512:  MediaType = "5.25, 1.2MB,  512 bytes/sector";break;
        case F3_1Pt44_512: MediaType = "3.5,  1.44MB, 512 bytes/sector";break;
        case F3_2Pt88_512: MediaType = "3.5,  2.88MB, 512 bytes/sector";break;
        case F3_20Pt8_512: MediaType = "3.5,  20.8MB, 512 bytes/sector";break;
        case F3_720_512:   MediaType = "3.5,  720KB,  512 bytes/sector";break;
        case F5_360_512:   MediaType = "5.25, 360KB,  512 bytes/sector";break;
        case F5_320_512:   MediaType = "5.25, 320KB,  512 bytes/sector";break;
        case F5_320_1024:  MediaType = "5.25, 320KB,  1024 bytes/sector";break;
        case F5_180_512:   MediaType = "5.25, 180KB,  512 bytes/sector";break;
        case F5_160_512:   MediaType = "5.25, 160KB,  512 bytes/sector";break;
        case RemovableMedia: MediaType = "Removable media other than floppy";break;
        case FixedMedia:   MediaType = "Fixed hard disk media";break;
        default:           MediaType = "Unknown";break;
    }
    printf("    Media Type %s\n",MediaType);
    printf("    Cylinders %d Tracks/Cylinder %d Sectors/Track %d\n",
        lpGeometry->Cylinders.LowPart,
        lpGeometry->TracksPerCylinder,
        lpGeometry->SectorsPerTrack
        );
}

BOOL
LowLevelFormat(
    HANDLE hDisk,
    PDISK_GEOMETRY lpGeometry
    )
{
    FORMAT_PARAMETERS FormatParameters;
    PBAD_TRACK_NUMBER lpBadTrack;
    UINT i;
    BOOL b;
    DWORD ReturnedByteCount;

    FormatParameters.MediaType = lpGeometry->MediaType;
    FormatParameters.StartHeadNumber = 0;
    FormatParameters.EndHeadNumber = lpGeometry->TracksPerCylinder - 1;
    lpBadTrack = (PBAD_TRACK_NUMBER) LocalAlloc(LMEM_ZEROINIT,lpGeometry->TracksPerCylinder*sizeof(*lpBadTrack));

    for (i = 0; i < lpGeometry->Cylinders.LowPart; i++) {

        FormatParameters.StartCylinderNumber = i;
        FormatParameters.EndCylinderNumber = i;

        b = DeviceIoControl(
                hDisk,
                IOCTL_DISK_FORMAT_TRACKS,
                &FormatParameters,
                sizeof(FormatParameters),
                lpBadTrack,
                lpGeometry->TracksPerCylinder*sizeof(*lpBadTrack),
                &ReturnedByteCount,
                NULL
                );

        if (!b ) {
            LocalFree(lpBadTrack);
            return b;
            }
        }

    LocalFree(lpBadTrack);

    return TRUE;
}

BOOL
LockVolume(
    HANDLE hDisk
    )
{
    DWORD ReturnedByteCount;

    return DeviceIoControl(
                hDisk,
                FSCTL_LOCK_VOLUME,
                NULL,
                0,
                NULL,
                0,
                &ReturnedByteCount,
                NULL
                );
}

BOOL
UnlockVolume(
    HANDLE hDisk
    )
{
    DWORD ReturnedByteCount;

    return DeviceIoControl(
                hDisk,
                FSCTL_UNLOCK_VOLUME,
                NULL,
                0,
                NULL,
                0,
                &ReturnedByteCount,
                NULL
                );
}

BOOL
DismountVolume(
    HANDLE hDisk
    )
{
    DWORD ReturnedByteCount;

    return DeviceIoControl(
                hDisk,
                FSCTL_DISMOUNT_VOLUME,
                NULL,
                0,
                NULL,
                0,
                &ReturnedByteCount,
                NULL
                );
}
//未完待续
赵4老师 2014-03-14
  • 打赏
  • 举报
回复
Locking and Unlocking Files Although the system allows more than one application to open a file and write to it, applications must not write over each other's work. An application can prevent this problem by temporarily locking a region in a file. The LockFile and LockFileEx functions lock a specified range of bytes in a file. The range may extend beyond the current end of the file. Locking part of a file prevents all other processes from reading or writing anywhere in the specified area. Attempts to read from or write to a region locked by another process always fail. The LockFileEx function allows an application to specify either a shared lock or an exclusive lock. An exclusive lock denies all other processes both read and write access to the specified region of the file. A shared lock denies all processes write access to the specified region of the file, including the process that first locks the region. This can be used to create a read-only region in a file. The application unlocks the region by using the UnlockFile or UnlockFileEx function. An application should unlock all locked areas before closing a file.
nevergone 2014-03-14
  • 打赏
  • 举报
回复
如果是XP系统,管理员权限可以直接写。 如果是vista+系统,看这个链接http://msdn.microsoft.com/en-us/library/windows/hardware/ff551353(v=vs.85).aspx 直接写不了MBR,要用驱动写才行。
nevergone 2014-03-14
  • 打赏
  • 举报
回复
我是来看赵四神棍笑话的 哈哈哈 贴了那么多不着边际的代码。
高小阳 2014-03-14
  • 打赏
  • 举报
回复
还有没有 大神能解决啊? 谢谢楼上那两位
高小阳 2014-03-14
  • 打赏
  • 举报
回复
我这没有程序占用啊 , 我之前也写成功过,不是总能写入,我拿u盘测试的,有的u盘直接能写,有的写不了
叶之香 2014-03-14
  • 打赏
  • 举报
回复
HANDLE h = CreateFileA("\\\\.\\PhysicalDrive0", GENERIC_READ | GENERIC_WRITE, FILE_SHARE_READ | FILE_SHARE_WRITE, NULL, OPEN_EXISTING, 0, NULL); if (INVALID_HANDLE_VALUE == h) { printf("Error : %d\n", GetLastError()); return 1; } 我这里能够成功,可能是你的有程序占用了
赵4老师 2014-03-14
  • 打赏
  • 举报
回复
FSCTL_LOCK_VOLUME The FSCTL_LOCK_VOLUME operation locks a volume. A locked volume can be accessed only through handles to the file object (*hDevice) that locks the volume. To perform this operation, call the DeviceIoControl function using the following parameters. BOOL DeviceIoControl( (HANDLE) hDevice, // handle to a file FSCTL_LOCK_VOLUME, // dwIoControlCode, control code of // operation to perform NULL, // lpInBuffer is not used; must be NULL 0, // nInBufferSize is not used; must be zero NULL, // lpOutBuffer is not used; must be NULL 0, // nOutBufferSize is not used; must be zero (LPDWORD) lpBytesReturned, // pointer to receive output byte count (LPOVERLAPPED) lpOverlapped // pointer to OVERLAPPED structure // for asynchronous operation ); Parameters hDevice Handle to the volume to be locked. To obtain a device handle, call the CreateFile function. dwIoControlCode Control code for the operation. This value identifies the specific operation to be performed and the type of device on which the operation is to be performed. Use FSCTL_LOCK_VOLUME for this operation. lpInBuffer Pointer to the input buffer. Not used; must be NULL. nInBufferSize Size, in bytes, of the input buffer. Not used; must be zero. lpOutBuffer Pointer to the output buffer. Not used; must be NULL nOutBufferSize Size, in bytes, of the output buffer. Not used; must be zero. lpBytesReturned Pointer to a DWORD variable. If lpOverlapped is NULL (nonoverlapped I/O), lpBytesReturned is used internally and cannot be NULL. If lpOverlapped is not NULL (overlapped I/O), lpBytesReturned can be NULL. lpOverlapped Pointer to an OVERLAPPED structure. If hDevice was opened with the FILE_FLAG_OVERLAPPED flag, this parameter must point to a valid OVERLAPPED structure. In this case, DeviceIoControl is performed as an overlapped (asynchronous) operation. If the device was opened with the FILE_FLAG_OVERLAPPED flag and lpOverlapped is NULL, the function fails in unpredictable ways. If hDevice was opened without specifying the FILE_FLAG_OVERLAPPED flag, this parameter is ignored and the DeviceIoControl function does not return until the operation has been completed, or until an error occurs. Return Values If the operation succeeds, DeviceIoControl returns a nonzero value. If the operation fails, DeviceIoControl returns zero. To get extended error information, call GetLastError. Remarks The hDevice handle passed to DeviceIoControl must be a handle to a volume, opened for direct access. An application can obtain such a handle by calling CreateFile with lpFileName set to a string that looks like this: \\.\X: where X is a hard-drive partition letter, floppy disk drive, or CD-ROM drive. The application must also specify the FILE_SHARE_READ and FILE_SHARE_WRITE flags in the dwShareMode parameter of CreateFile. The FSCTL_LOCK_VOLUME operation fails if there are any open files on the volume. Conversely, success of this operation indicates there are no open files. The operation is useful for applications that need exclusive access to a volume for a period of time—for example, disk utility programs. A locked volume remains locked until one of the following occurs: The application invokes the FSCTL_UNLOCK_VOLUME DeviceIoControl operation to unlock the volume. The handle closes, either directly through CloseHandle, or indirectly when a process terminates. The system flushes all cached data to the volume before locking it. For example, any data held in a lazy-write cache is written to the volume. QuickInfo Windows NT: Requires version 3.5 or later. Windows: Unsupported. Windows CE: Unsupported. Header: Declared in winioctl.h. See Also Device Input and Output Overview, Device Input and Output Operations, CloseHandle, CreateFile, DeviceIoControl, FSCTL_UNLOCK_VOLUME
加载更多回复(5)

3,881

社区成员

发帖
与我相关
我的任务
社区描述
C/C++ 其它技术问题
社区管理员
  • 其它技术问题社区
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧