Problem in CreateFile Function


DevX Home    Today's Headlines   Articles Archive   Tip Bank   Forums   

Results 1 to 9 of 9

Thread: Problem in CreateFile Function

  1. #1
    Join Date
    Aug 2004
    Posts
    43,023

    Problem in CreateFile Function

    [Originally posted by Mahesh]

    Hey,
      I have a problem using createfile function.it works well in win2000 or NT but returns a error -1 in win98.How can i get correct results also in win 98.Please help me

  2. #2
    Join Date
    Aug 2004
    Posts
    43,023

    Re:Problem in CreateFile Function

    [Originally posted by neophile]

    What's your code look like?

  3. #3
    Join Date
    Aug 2004
    Posts
    43,023

    Re:Problem in CreateFile Function

    [Originally posted by anitha]

    Hi,
    Did you get an answer for the CreateFile problem in Win 98 ??
    If so can you please let me know.

    Thanks,
    Anitha

  4. #4
    Join Date
    Aug 2004
    Posts
    43,023

    Re:Re:Problem in CreateFile Function

    [Originally posted by santosh]

    I think u can try using this code, this is a small sample which i used:

    Dim fs
    Dim a

    Set fs = CreateObject("Scripting.FileSystemObject")

    a = fs.fileexists(App.Path & "\Backup\user.dit")
    If a = False Then
    Set a = fs.createtextFile(App.Path & "\Backup\user.dit")
    End If


    cheers
    santosh

  5. #5
    Join Date
    Aug 2004
    Posts
    43,023

    Re:Problem in CreateFile Function

    [Originally posted by Thanos Naranja]

    The CreateFile API does not work in the Win98/95 environment. It was never desigend to do so. Trust me, I have discussed this with professional programmers that have written books on the subject. The reason; the API is not available in Win98 system DLLs.

    As suggested, use the FileSystemObject.

  6. #6
    Join Date
    Aug 2004
    Posts
    43,023

    Re:Re:Problem in CreateFile Function

    [Originally posted by m.posseth]

    hmmm those experts should have done some better homework :-)


    because the api guide tells me that

    min required OS : Requires Windows NT 3.1 or later; Requires Windows 95 or later...

    Declare Function CreateFile Lib "kernel32" Alias "CreateFileA" (ByVal lpFileName As String, ByVal dwDesiredAccess As Long, ByVal dwShareMode As Long, lpSecurityAttributes As SECURITY_ATTRIBUTES, ByVal dwCreationDisposition As Long, ByVal dwFlagsAndAttributes As Long, ByVal hTemplateFile As Long) As Long


    lpFileName
    Points to a null-terminated string that specifies the name of the object (file, pipe, mailslot, communications resource, disk device, console, or directory) to create or open.
    If *lpFileName is a path, there is a default string size limit of MAX_PATH characters. This limit is related to how the CreateFile function parses paths.
    Windows NT: You can use paths longer than MAX_PATH characters by calling the wide (W) version of CreateFile and prepending "\\?\" to the path. The "\\?\" tells the function to turn off path parsing. This lets you use paths that are nearly 32,000 Unicode characters long. You must use fully-qualified paths with this technique. This also works with UNC names. The "\\?\" is ignored as part of the path. For example, "\\?\C:\myworld\private" is seen as "C:\myworld\private", and "\\?\UNC\tom_1\hotstuff\coolapps" is seen as "\\tom_1\hotstuff\coolapps".

    dwDesiredAccess
    Specifies the type of access to the object. An application can obtain read access, write access, read-write access, or device query access. This parameter can be any combination of the following values.
    0
    Specifies device query access to the object. An application can query device attributes without accessing the device.
    GENERIC_READ
    Specifies read access to the object. Data can be read from the file and the file pointer can be moved. Combine with GENERIC_WRITE for read-write access.
    GENERIC_WRITE
    Specifies write access to the object. Data can be written to the file and the file pointer can be moved. Combine with GENERIC_READ for read-write access.

    dwShareMode
    Set of bit flags that specifies how the object can be shared. If dwShareMode is 0, the object cannot be shared. Subsequent open operations on the object will fail, until the handle is closed.
    To share the object, use a combination of one or more of the following values:
    FILE_SHARE_DELETE
    Windows NT only: Subsequent open operations on the object will succeed only if delete access is requested.
    FILE_SHARE_READ
    Subsequent open operations on the object will succeed only if read access is requested.
    FILE_SHARE_WRITE
    Subsequent open operations on the object will succeed only if write access is requested.

    lpSecurityAttributes
    Pointer to a SECURITY_ATTRIBUTES structure that determines whether the returned handle can be inherited by child processes. If lpSecurityAttributes is NULL, the handle cannot be inherited.
    Windows NT: The lpSecurityDescriptor member of the structure specifies a security descriptor for the object. If lpSecurityAttributes is NULL, the object gets a default security descriptor. The target file system must support security on files and directories for this parameter to have an effect on files.
    Windows 95: The lpSecurityDescriptor member of the structure is ignored.

    dwCreationDistribution
    Specifies which action to take on files that exist, and which action to take when files do not exist. For more information about this parameter, see the Remarks section. This parameter must be one of the following values:
    CREATE_NEW
    Creates a new file. The function fails if the specified file already exists.
    CREATE_ALWAYS
    Creates a new file. The function overwrites the file if it exists.
    OPEN_EXISTING
    Opens the file. The function fails if the file does not exist.
    See the Remarks section for a discussion of why you should use the OPEN_EXISTING flag if you are using the CreateFile function for devices, including the console.
    OPEN_ALWAYS
    Opens the file, if it exists. If the file does not exist, the function creates the file as if dwCreationDistribution were CREATE_NEW.
    TRUNCATE_EXISTING
    Opens the file. Once opened, the file is truncated so that its size is zero bytes. The calling process must open the file with at least GENERIC_WRITE access. The function fails if the file does not exist.

    dwFlagsAndAttributes
    Specifies the file attributes and flags for the file.
    Any combination of the following attributes is acceptable for the dwFlagsAndAttributes parameter, except all other file attributes override FILE_ATTRIBUTE_NORMAL.
    FILE_ATTRIBUTE_ARCHIVE
    The file should be archived. Applications use this attribute to mark files for backup or removal.
    FILE_ATTRIBUTE_COMPRESSED
    The file or directory is compressed. For a file, this means that all of the data in the file is compressed. For a directory, this means that compression is the default for newly created files and subdirectories.
    FILE_ATTRIBUTE_HIDDEN
    The file is hidden. It is not to be included in an ordinary directory listing.
    FILE_ATTRIBUTE_NORMAL
    The file has no other attributes set. This attribute is valid only if used alone.
    FILE_ATTRIBUTE_OFFLINE
    The data of the file is not immediately available. Indicates that the file data has been physically moved to offline storage.
    FILE_ATTRIBUTE_READONLY
    The file is read only. Applications can read the file but cannot write to it or delete it.
    FILE_ATTRIBUTE_SYSTEM
    The file is part of or is used exclusively by the operating system.
    FILE_ATTRIBUTE_TEMPORARY
    The file is being used for temporary storage. File systems attempt to keep all of the data in memory for quicker access rather than flushing the data back to mass storage. A temporary file should be deleted by the application as soon as it is no longer needed.

    Any combination of the following flags is acceptable for the dwFlagsAndAttributes parameter.
    FILE_FLAG_WRITE_THROUGH
    Instructs the system to write through any intermediate cache and go directly to disk. Windows can still cache write operations, but cannot lazily flush them.
    FILE_FLAG_OVERLAPPED
    Instructs the system to initialize the object, so that operations that take a significant amount of time to process return ERROR_IO_PENDING. When the operation is finished, the specified event is set to the signaled state.
    When you specify FILE_FLAG_OVERLAPPED, the ReadFile and WriteFile functions must specify an OVERLAPPED structure. That is, when FILE_FLAG_OVERLAPPED is specified, an application must perform overlapped reading and writing.
    When FILE_FLAG_OVERLAPPED is specified, the system does not maintain the file pointer. The file position must be passed as part of the lpOverlapped parameter (pointing to an OVERLAPPED structure) to the ReadFile and WriteFile functions.
    This flag also enables more than one operation to be performed simultaneously with the handle (a simultaneous read and write operation, for example).
    FILE_FLAG_NO_BUFFERING
    Instructs the system to open the file with no intermediate buffering or caching. When combined with FILE_FLAG_OVERLAPPED, the flag gives maximum asynchronous performance, because the I/O does not rely on the synchronous operations of the memory manager. However, some I/O operations will take longer, because data is not being held in the cache.
    An application must meet certain requirements when working with files opened with FILE_FLAG_NO_BUFFERING:
    File access must begin at byte offsets within the file that are integer multiples of the volume's sector size.
    File access must be for numbers of bytes that are integer multiples of the volume's sector size. For example, if the sector size is 512 bytes, an application can request reads and writes of 512, 1024, or 2048 bytes, but not of 335, 981, or 7171 bytes.
    Buffer addresses for read and write operations must be aligned on addresses in memory that are integer multiples of the volume's sector size.
    One way to align buffers on integer multiples of the volume sector size is to use VirtualAlloc to allocate the buffers. It allocates memory that is aligned on addresses that are integer multiples of the operating system's memory page size. Because both memory page and volume sector sizes are powers of 2, this memory is also aligned on addresses that are integer multiples of a volume's sector size.
    An application can determine a volume's sector size by calling the GetDiskFreeSpace function.
    FILE_FLAG_RANDOM_ACCESS
    Indicates that the file is accessed randomly. The system can use this as a hint to optimize file caching.
    FILE_FLAG_SEQUENTIAL_SCAN
    Indicates that the file is to be accessed sequentially from beginning to end. The system can use this as a hint to optimize file caching. If an application moves the file pointer for random access, optimum caching may not occur; however, correct operation is still guaranteed.
    Specifying this flag can increase performance for applications that read large files using sequential access. Performance gains can be even more noticeable for applications that read large files mostly sequentially, but occasionally skip over small ranges of bytes.
    FILE_FLAG_DELETE_ON_CLOSE
    Indicates that the operating system is to delete the file immediately after all of its handles have been closed, not just the handle for which you specified FILE_FLAG_DELETE_ON_CLOSE.
    Subsequent open requests for the file will fail, unless FILE_SHARE_DELETE is used.
    FILE_FLAG_BACKUP_SEMANTICS
    Windows NT only: Indicates that the file is being opened or created for a backup or restore operation. The operating system ensures that the calling process overrides file security checks, provided it has the necessary permission to do so. The relevant permissions are SE_BACKUP_NAME and SE_RESTORE_NAME.
    You can also set this flag to obtain a handle to a directory. A directory handle can be passed to some Win32 functions in place of a file handle.
    FILE_FLAG_POSIX_SEMANTICS
    Indicates that the file is to be accessed according to POSIX rules. This includes allowing multiple files with names, differing only in case, for file systems that support such naming. Use care when using this option because files created with this flag may not be accessible by applications written for MS-DOS or Windows.

    If the CreateFile function opens the client side of a named pipe, the dwFlagsAndAttributes parameter can also contain Security Quality of Service information. When the calling application specifies the SECURITY_SQOS_PRESENT flag, the dwFlagsAndAttributes parameter can contain one or more of the following values:
    SECURITY_ANONYMOUS
    Specifies to impersonate the client at the Anonymous impersonation level.
    SECURITY_IDENTIFICATION
    Specifies to impersonate the client at the Identification impersonation level.
    SECURITY_IMPERSONATION
    Specifies to impersonate the client at the Impersonation impersonation level.
    SECURITY_DELEGATION
    Specifies to impersonate the client at the Delegation impersonation level.
    SECURITY_CONTEXT_TRACKING
    Specifies that the security tracking mode is dynamic. If this flag is not specified, Security Tracking Mode is static.
    SECURITY_EFFECTIVE_ONLY
    Specifies that only the enabled aspects of the client's security context are available to the server. If you do not specify this flag, all aspects of the client's security context are available.
    This flag allows the client to limit the groups and privileges that a server can use while impersonating the client.

    hTemplateFile
    Specifies a handle with GENERIC_READ access to a template file. The template file supplies file attributes and extended attributes for the file being created.


    and now it comes !!!!!!!
    Windows 95: This value must be NULL. If you supply a handle under Windows 95, the call fails and GetLastError returns ERROR_NOT_SUPPORTED.

    If the function succeeds, the return value is an open handle to the specified file. If the specified file exists before the function call and dwCreationDistribution is CREATE_ALWAYS or OPEN_ALWAYS, a call to GetLastError returns ERROR_ALREADY_EXISTS (even though the function has succeeded). If the file does not exist before the call, GetLastError returns zero.

    If the function fails, the return value is INVALID_HANDLE_VALUE. To get extended error information, call GetLastError.


    read and write example ::::::

    Const MOVEFILE_REPLACE_EXISTING = &H1
    Const FILE_ATTRIBUTE_TEMPORARY = &H100
    Const FILE_BEGIN = 0
    Const FILE_SHARE_READ = &H1
    Const FILE_SHARE_WRITE = &H2
    Const CREATE_NEW = 1
    Const OPEN_EXISTING = 3
    Const GENERIC_READ = &H80000000
    Const GENERIC_WRITE = &H40000000
    Private Declare Function SetVolumeLabel Lib "kernel32" Alias "SetVolumeLabelA" (ByVal lpRootPathName As String, ByVal lpVolumeName As String) As Long
    Private Declare Function WriteFile Lib "kernel32" (ByVal hFile As Long, lpBuffer As Any, ByVal nNumberOfBytesToWrite As Long, lpNumberOfBytesWritten As Long, ByVal lpOverlapped As Any) As Long
    Private Declare Function ReadFile Lib "kernel32" (ByVal hFile As Long, lpBuffer As Any, ByVal nNumberOfBytesToRead As Long, lpNumberOfBytesRead As Long, ByVal lpOverlapped As Any) As Long
    Private Declare Function CreateFile Lib "kernel32" Alias "CreateFileA" (ByVal lpFileName As String, ByVal dwDesiredAccess As Long, ByVal dwShareMode As Long, ByVal lpSecurityAttributes As Any, ByVal dwCreationDisposition As Long, ByVal dwFlagsAndAttributes As Long, ByVal hTemplateFile As Long) As Long
    Private Declare Function CloseHandle Lib "kernel32" (ByVal hObject As Long) As Long
    Private Declare Function SetFilePointer Lib "kernel32" (ByVal hFile As Long, ByVal lDistanceToMove As Long, lpDistanceToMoveHigh As Long, ByVal dwMoveMethod As Long) As Long
    Private Declare Function SetFileAttributes Lib "kernel32" Alias "SetFileAttributesA" (ByVal lpFileName As String, ByVal dwFileAttributes As Long) As Long
    Private Declare Function GetFileSize Lib "kernel32" (ByVal hFile As Long, lpFileSizeHigh As Long) As Long
    Private Declare Function GetTempFileName Lib "kernel32" Alias "GetTempFileNameA" (ByVal lpszPath As String, ByVal lpPrefixString As String, ByVal wUnique As Long, ByVal lpTempFileName As String) As Long
    Private Declare Function MoveFileEx Lib "kernel32" Alias "MoveFileExA" (ByVal lpExistingFileName As String, ByVal lpNewFileName As String, ByVal dwFlags As Long) As Long
    Private Declare Function DeleteFile Lib "kernel32" Alias "DeleteFileA" (ByVal lpFileName As String) As Long
    Private Sub Form_Load()
    'KPD-Team 1998
    'URL: http://www.allapi.net/
    'E-Mail: KPDTeam@Allapi.net
    Dim sSave As String, hOrgFile As Long, hNewFile As Long, bBytes() As Byte
    Dim sTemp As String, nSize As Long, Ret As Long
    'Ask for a new volume label
    sSave = InputBox("Please enter a new volume label for drive C:\" + vbCrLf + " (if you don't want to change it, leave the textbox blank)")
    If sSave <> "" Then
    SetVolumeLabel "C:\", sSave
    End If

    'Create a buffer
    sTemp = String(260, 0)
    'Get a temporary filename
    GetTempFileName "C:\", "KPD", 0, sTemp
    'Remove all the unnecessary chr$(0)'s
    sTemp = Left$(sTemp, InStr(1, sTemp, Chr$(0)) - 1)
    'Set the file attributes
    SetFileAttributes sTemp, FILE_ATTRIBUTE_TEMPORARY
    'Open the files
    hNewFile = CreateFile(sTemp, GENERIC_WRITE, FILE_SHARE_READ Or FILE_SHARE_WRITE, ByVal 0&, OPEN_EXISTING, 0, 0)
    hOrgFile = CreateFile("c:\config.sys", GENERIC_READ, FILE_SHARE_READ Or FILE_SHARE_WRITE, ByVal 0&, OPEN_EXISTING, 0, 0)

    'Get the file size
    nSize = GetFileSize(hOrgFile, 0)
    'Set the file pointer
    SetFilePointer hOrgFile, Int(nSize / 2), 0, FILE_BEGIN
    'Create an array of bytes
    ReDim bBytes(1 To nSize - Int(nSize / 2)) As Byte
    'Read from the file
    ReadFile hOrgFile, bBytes(1), UBound(bBytes), Ret, ByVal 0&
    'Check for errors
    If Ret <> UBound(bBytes) Then MsgBox "Error reading file ..."

    'Write to the file
    WriteFile hNewFile, bBytes(1), UBound(bBytes), Ret, ByVal 0&
    'Check for errors
    If Ret <> UBound(bBytes) Then MsgBox "Error writing file ..."

    'Close the files
    CloseHandle hOrgFile
    CloseHandle hNewFile

    'Move the file
    MoveFileEx sTemp, "C:\KPDTEST.TST", MOVEFILE_REPLACE_EXISTING
    'Delete the file
    DeleteFile "C:\KPDTEST.TST"
    Unload Me
    End Sub



    all the above is from the API GUIDE 3.7

    just download it from www.allapi.net

    it costs you a postcard !!! ( it is postcard ware meaning that the developers of the api guide would like it if you would send them a postcard from the city that you live ,,,, believe me it is a live saver !!!! )






  7. #7
    Join Date
    Aug 2004
    Posts
    43,023

    Re:Problem in CreateFile Function

    [Originally posted by vamsy]


    SUB--REG. UR QUESTION IN VB


    Hi! My name is vamsy and i am doing my Btech.

    U Did not decribe ur problem in detail, however i will try to guess it and answer it-

    CreateFile has so many params that are dependent on the OS.Since Win2000 has the same architecture as WinNT all the apis for the winNT Should work for 2000 too.As for the win9x the params are slightly different.

    NOTE THAT THE ARG 'hTemplateFile' Which Specifies a handle with GENERIC_READ access to a template file( The template file supplies file attributes and extended attributes for the file being created)Is only for the WINNT. It fails on win9x machines!
    'hTemplateFile' SHOULD BE NULL IN WIN9X or else the call fails!

    Also to access the disk devices in-

    1.Windows NT: You can use the CreateFile function to open a disk drive or a partition on a disk drive. The function returns a handle to the disk device; that handle can be used with the DeviceIOControl function. The following requirements must be met in order for such a call to succeed:

    The caller must have administrative privileges for the operation to succeed on a hard disk drive.


    The lpFileName string should be of the form \\.\PHYSICALDRIVEx to open the hard disk x. Hard disk numbers start at zero. For example:

    String Meaning
    \\.\PHYSICALDRIVE2 Obtains a handle to the third physical drive on the user's computer.

    The lpFileName string should be \\.\x: to open a floppy drive x or a partition x on a hard disk. For example:

    String Meaning
    \\.\A: Obtains a handle to drive A on the user's computer.
    \\.\C: Obtains a handle to drive C on the user's computer.

    2.Windows 95: This technique does not work for opening a logical drive. In Windows 95, specifying a string in this form causes CreateFile to return an error.

    The dwCreationDistribution parameter must have the OPEN_EXISTING value.

    When opening a floppy disk or a partition on a hard disk, you must set the FILE_SHARE_WRITE flag in the dwShareMode parameter.

  8. #8
    Join Date
    Aug 2004
    Posts
    43,023

    Re:Re:Re:Problem in CreateFile Function

    [Originally posted by Thanos Naranja]

    It also fails under Win98. I wonder why Microsoft TechNet Application Experts for the VBIDE could not answer this question? In any case it is too late now . All my code is designed around the FSO. Then again, I don't know, the FSO seems so much more elegant in code and execution, more straight forward. Thanks guys...

  9. #9
    Join Date
    Aug 2004
    Posts
    43,023

    Re:Re:Re:Re:Problem in CreateFile Function

    [Originally posted by anitha]

    Thanks guys !!

    I used FSO and created the file.


Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  
HTML5 Development Center
 
 
FAQ
Latest Articles
Java
.NET
XML
Database
Enterprise
Questions? Contact us.
C++
Web Development
Wireless
Latest Tips
Open Source


   Development Centers

   -- Android Development Center
   -- Cloud Development Project Center
   -- HTML5 Development Center
   -- Windows Mobile Development Center