Formatar disquete em Fat12

Preciso fazer um programa q formate um disquete em fat12, isso tudo usando RMI. Gostaria de saber como faço isso. Ou pelo menos como posso formatar esse disquete sem usar RMI. Já tentei fazer chamando o cmd, mas ñ gostei do resultado. Por favor me ajudem. Valeu.

Eu tive de formatar um disquete com o seguinte comando:

format.com /q /y /v:VOLUME a:

(onde /q força o programa a não mostrar nada, /v:VOLUME o nome que você vai dar ao disquete, e /y força a não pedir para teclar nada. )

No caso do Windows 2000:

format.com /q /backup /v:VOLUME a:

No caso do Windows 9X/ME:

format.com /q /autotest /v:VOLUME a:

Portanto, você tem de identificar qual é a versão do Windows que você está usando (se 2000, 9X/ME ou então qualquer outro), e usar o comando adequado.

[quote=thingol]Eu tive de formatar um disquete com o seguinte comando:

format.com /q /y /v:VOLUME a:

(onde /q força o programa a não mostrar nada, /v:VOLUME o nome que você vai dar ao disquete, e /y força a não pedir para teclar nada. )

No caso do Windows 2000:

format.com /q /backup /v:VOLUME a:

No caso do Windows 9X/ME:

format.com /q /autotest /v:VOLUME a:

Portanto, você tem de identificar qual é a versão do Windows que você está usando (se 2000, 9X/ME ou então qualquer outro), e usar o comando adequado.

[/quote]

O problema eh esse, primeiro eu tenho q fazer um formatador em fat12 e ñ usar o do windows q no meu caso eh o xp. Além disso tenho q fazer isso em todas as plataformas e ainda usando rmi. Eu fiz mascarando o prompt mas ñ gostei do resultado. Vc tem ideia como faço isso? Obrigado.

Para acessar diretamente o disquete, se você for escrever um programa em C, você teria de ter as permissões adequadas (no caso do Windows Vista isso é sempre um problema muito sério), e precisa fazer uns truques. Vou mostrar abaixo um programa em C que copia um disquete em outro (mas não faz a formatação, que envolve gravar uma seqüência especial de bytes no começo do disquete).


/******************************************************************************\
*       This is a part of the Microsoft Source Code Samples.
*       Copyright (C) 1993-1997 Microsoft Corporation.
*       All rights reserved.
*       This source code is only intended as a supplement to
*       Microsoft Development Tools and/or WinHelp documentation.
*       See these sources for detailed information regarding the
*       Microsoft samples programs.
\******************************************************************************/

/*++

Module Name:

    mfmt.c

Abstract:

    This program is designed to show how to access a physical floppy
    disk using the Win32 API set.

    This program has two major functions.

        - It can be used to display the geometry of a disk

            mfmt -g a:

        - It can be used to produce a disk image, or to write a disk
          image to a floppy.

            mfmt -c a: bootdisk         - produce a disk image of a:

            mfmt -c bootdisk a:         - make a: identical to bootdisk image

    This program is very very simple. Minimal error checking is done. It is
    meant to provide an example of how to:

        - Open a physical disk

        - Read a disk's geometry

        - Perform a low level format operation

        - read and write physical sectors

--*/

#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;
    fprintf (stderr, "\nFormatting....\r");
    lpBadTrack = (PBAD_TRACK_NUMBER) LocalAlloc(LMEM_ZEROINIT,lpGeometry->TracksPerCylinder*sizeof(*lpBadTrack));

    for (i = 0; i < lpGeometry->Cylinders.LowPart; i++) {
        fprintf (stderr, "Formatting track %d\r", 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);
            fprintf (stderr, "\nError formatting track %d\n", i);
            return b;
            }
        }

    LocalFree(lpBadTrack);
    fprintf (stderr, "\nDisk formatted.\n");
    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
                );
}

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;
    BOOL formatfirst;

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

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

                case 'g': 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" );
        printf("            [-C source destination] produce diskimage without formatting first\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;
            DWORD TotBytes;

            //
            // 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);
                    }
                fprintf (stderr, "Copying from the floppy...\n");
                TotBytes = 0;
                for ( ;NumBufs > 0; NumBufs-- )
                    {
                    fprintf (stderr, "Reading pos %d...\r", TotBytes);
                    b = ReadFile(hDrive,IoBuffer, VirtBufSize, &BytesRead, NULL);
                    if (b && BytesRead){
                    	TotBytes += 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
                        //
						if (formatfirst)
                        	LowLevelFormat(hDrive,&SupportedGeometry[i]);

			TotBytes = 0;
                        for ( ;NumBufs > 0; NumBufs-- )
                            {
                            b = ReadFile(hDiskImage,IoBuffer, VirtBufSize, &BytesRead, NULL);
                            if (b && BytesRead){
                            	fprintf (stderr, "Writing pos %d\r", TotBytes);
                                b = WriteFile(hDrive,IoBuffer, BytesRead, &BytesWritten, NULL);
                                TotBytes += BytesWritten;
                                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);
}

[quote=thingol]Para acessar diretamente o disquete, se você for escrever um programa em C, você teria de ter as permissões adequadas (no caso do Windows Vista isso é sempre um problema muito sério), e precisa fazer uns truques. Vou mostrar abaixo um programa em C que copia um disquete em outro (mas não faz a formatação, que envolve gravar uma seqüência especial de bytes no começo do disquete).

[code]

/******************************************************************************\

  •   This is a part of the Microsoft Source Code Samples.
    
  •   Copyright (C) 1993-1997 Microsoft Corporation.
    
  •   All rights reserved.
    
  •   This source code is only intended as a supplement to
    
  •   Microsoft Development Tools and/or WinHelp documentation.
    
  •   See these sources for detailed information regarding the
    
  •   Microsoft samples programs.
    

******************************************************************************/

/*++

Module Name:

mfmt.c

Abstract:

This program is designed to show how to access a physical floppy
disk using the Win32 API set.

This program has two major functions.

    - It can be used to display the geometry of a disk

        mfmt -g a:

    - It can be used to produce a disk image, or to write a disk
      image to a floppy.

        mfmt -c a: bootdisk         - produce a disk image of a:

        mfmt -c bootdisk a:         - make a: identical to bootdisk image

This program is very very simple. Minimal error checking is done. It is
meant to provide an example of how to:

    - Open a physical disk

    - Read a disk's geometry

    - Perform a low level format operation

    - read and write physical sectors

–*/

#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(&quot;Geometry for Drive %s\n&quot;,lpDriveName);
    }

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

}

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

FormatParameters.MediaType = lpGeometry-&gt;MediaType;
FormatParameters.StartHeadNumber = 0;
FormatParameters.EndHeadNumber = lpGeometry-&gt;TracksPerCylinder - 1;
fprintf (stderr, &quot;\nFormatting....\r&quot;);
lpBadTrack = (PBAD_TRACK_NUMBER) LocalAlloc(LMEM_ZEROINIT,lpGeometry-&gt;TracksPerCylinder*sizeof(*lpBadTrack));

for (i = 0; i &lt; lpGeometry-&gt;Cylinders.LowPart; i++) {
    fprintf (stderr, &quot;Formatting track %d\r&quot;, i);
    FormatParameters.StartCylinderNumber = i;
    FormatParameters.EndCylinderNumber = i;

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

    if (!b ) {
        LocalFree(lpBadTrack);
        fprintf (stderr, &quot;\nError formatting track %d\n&quot;, i);
        return b;
        }
    }

LocalFree(lpBadTrack);
fprintf (stderr, &quot;\nDisk formatted.\n&quot;);
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
            );

}

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;
BOOL formatfirst;

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

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

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

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

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

if ( fShowGeometry ) {
    sprintf(Drive,&quot;\\\\.\\%s&quot;,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(&quot;MFMT: Open %s failed %d\n&quot;,DriveName,GetLastError());
        ExitProcess(1);
        }

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

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

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

    for(i=0;i&lt;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;
        DWORD TotBytes;

        //
        // 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);
                }
            fprintf (stderr, "Copying from the floppy...\n");
            TotBytes = 0;
            for ( ;NumBufs &gt; 0; NumBufs-- )
                {
                fprintf (stderr, "Reading pos %d...\r", TotBytes);
                b = ReadFile(hDrive,IoBuffer, VirtBufSize, &BytesRead, NULL);
                if (b && BytesRead){
                	TotBytes += 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&lt;SupportedGeometryCount;i++) {
                NumBufs = SupportedGeometry[i].Cylinders.LowPart;
                VirtBufSize =  SupportedGeometry[i].TracksPerCylinder *
                               SupportedGeometry[i].SectorsPerTrack *
                               SupportedGeometry[i].BytesPerSector;
                if ( VirtBufSize*NumBufs &gt;= FileSize ) {

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

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

                    //
                    // Format the floppy
                    //
					if (formatfirst)
                    	LowLevelFormat(hDrive,&SupportedGeometry[i]);

		TotBytes = 0;
                    for ( ;NumBufs &gt; 0; NumBufs-- )
                        {
                        b = ReadFile(hDiskImage,IoBuffer, VirtBufSize, &BytesRead, NULL);
                        if (b && BytesRead){
                        	fprintf (stderr, &quot;Writing pos %d\r&quot;, TotBytes);
                            b = WriteFile(hDrive,IoBuffer, BytesRead, &BytesWritten, NULL);
                            TotBytes += BytesWritten;
                            if ( !b || ( BytesRead != BytesWritten ) ) {
                                printf(&quot;MFMT: Fatal Write Error %d\n&quot;,GetLastError());
                                ExitProcess(1);
                                }
                            }
                        else {
                            printf(&quot;MFMT: Fatal Read Error %d\n&quot;,GetLastError());
                            ExitProcess(1);
                            }
                        }
                    b = TRUE;
                    break;
                	}
                }

            if ( !b ) {
                printf(&quot;MFMT: FileSize %d is not supported on drive %s\n&quot;,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);

}
[/code][/quote]
E vc tem alguma ideia como faço isso no java?
E tb como formato o disquete mesmo q ñ seja em fat12?
Obrigado.

Java não serve para formatar disquetes.
Ele serve para muitas outras coisas; se for para formatar um disquete, ele tem de chamar um programa escrito em outra linguagem. No meu caso, se você não quer usar o format.com do Windows, que é a única ferramenta do Windows que não vai ficar mostrando uma caixinha de diálogo no Windows Vista pedindo para usar poderes de administrador para poder formatar o disquete, você tem de achar um programa em C, Delphi ou sei lá o quê, que faça isso por você. Eu já até lhe passei o tal programa em C que faz a formatação física; para fazer a formatação lógica a maneira mais fácil é fazer uma cópia dos primeiros setores de um disquete que já esteja formatado.
Em um programa grande em Java que está rodando em vários clientes, efetuo a formatação de um disquete exatamente com a lógica que lhe passei (identifico o sistema operacional, e chamo o format.com com os parâmetros adequados. )

Se for formatar um disquete em Linux, então você precisa executar 2 comandos, dependendo de sua distribuição:

fdformat /dev/fd0H1440
mformat a:

De qualquer maneira, você tem de identificar a plataforma. Não tem nada que venha junto com o JDK e que sirva para formatar disquetes.

[quote=thingol]Java não serve para formatar disquetes.
Ele serve para muitas outras coisas; se for para formatar um disquete, ele tem de chamar um programa escrito em outra linguagem. No meu caso, se você não quer usar o format.com do Windows, que é a única ferramenta do Windows que não vai ficar mostrando uma caixinha de diálogo no Windows Vista pedindo para usar poderes de administrador para poder formatar o disquete, você tem de achar um programa em C, Delphi ou sei lá o quê, que faça isso por você. Eu já até lhe passei o tal programa em C que faz a formatação física; para fazer a formatação lógica a maneira mais fácil é fazer uma cópia dos primeiros setores de um disquete que já esteja formatado.
Em um programa grande em Java que está rodando em vários clientes, efetuo a formatação de um disquete exatamente com a lógica que lhe passei (identifico o sistema operacional, e chamo o format.com com os parâmetros adequados. )

Se for formatar um disquete em Linux, então você precisa executar 2 comandos, dependendo de sua distribuição:

fdformat /dev/fd0H1440
mformat a:

De qualquer maneira, você tem de identificar a plataforma. Não tem nada que venha junto com o JDK e que sirva para formatar disquetes.

[/quote]
Obrigado pela ajuda. Vou v se consigo fazer o desejado. Blz

Já que o problema eh portabilidade, não serve apenas apagar os dados do disquete? Aí daria pra fazer utilizando I/O.

Quanto ao RMI, eh soh a forma de invocação (remota) ao que vc quer fazer (formatar disquete).

Flw.

Chamar um .batzinho básico não rola?

Ressucitando o tópico…
Desculpe pela simplicidade da pergunta, mas como fazer para chamar o format do windows de dentro do java?
Preciso formatar um pendrive ou cartão de memória em um programa que estou fazendo.

Agradeço qualquer ajuda! Abraço!