Help with CreateFile...

Can anyone provide a sample of using CreateFile to open a file for read/write access and if the file does not exist, create it.  In both cases, returning a handle to the file to work with from that point onward.

I've tried to play around with CreateFile and it just isn't working out for me.  

So any help or even advice so i can understand it all better would be welcomed.
mi6agentAsked:
Who is Participating?
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

mokuleCommented:
var
      fHandle: THandle;
      Filename: string;
      nWritten: cardinal;
      nWrite: cardinal;
      buffer: string;
begin
    Filename := 'C:\test.txt';
    fHandle := CreateFile(PChar(Filename),GENERIC_READ or GENERIC_WRITE,  FILE_SHARE_READ or FILE_SHARE_WRITE, nil, CREATE_ALWAYS, 0, 0);
    buffer := 'something';
    nWrite := Length(buffer);
    WriteFile(fHandle,PChar(buffer), nWrite, nWritten, nil);
    CloseFile(fHandle);
0
mi6agentAuthor Commented:
I used

fhandle:=CreateFile(PChar(pathandfilename),
                         GENERIC_READ or GENERIC_WRITE,
                         FILE_SHARE_READ or FILE_SHARE_WRITE,
                         nil,
                         OPEN_ALWAYS,
                         FILE_ATTRIBUTE_NORMAL or FILE_FLAG_RANDOM_ACCESS,
                         0);

if fhandle=INVALID_HANDLE_VALUE  <== flag error else continue

as i wanted it to open the file if it exists or create it if it didn't BUT - i keep getting ERROR_NET_WRITE_FAULT and Access is denied (when i check via getlasterror).

0
HypoviaxCommented:
You can use the fileexists function to check if the file exists:

if fileexists(pchar(filename)) then
open_file_code
else
begin
fhandle:=CreateFile(PChar(pathandfilename),
                         GENERIC_READ or GENERIC_WRITE,
                         FILE_SHARE_READ or FILE_SHARE_WRITE,
                         nil,
                         OPEN_ALWAYS,
                         FILE_ATTRIBUTE_NORMAL or FILE_FLAG_RANDOM_ACCESS,
                         0);
end;

Regards,

Hypoviax
0
Cloud Class® Course: MCSA MCSE Windows Server 2012

This course teaches how to install and configure Windows Server 2012 R2.  It is the first step on your path to becoming a Microsoft Certified Solutions Expert (MCSE).

DragonSlayerCommented:
perhaps the file you wanted is on a Network share and you do not have the privileges to access it?
0
geobulCommented:
Hi,

mi6agent, your code seems correct. It might be priviledges as DragonSlayer said but it might also be wrong file path. What is the content of pathandfilename variable? UNC file name like
\\computername\sahedresource\filename
or something else?

If the filename is correct then try to open the file for read-only:

fhandle:=CreateFile(PChar(pathandfilename),
                         GENERIC_READ,
                         FILE_SHARE_READ or FILE_SHARE_WRITE,
                         nil,
                         OPEN_EXISTING,
                         0,
                         0);

If the above doesn't fail then you don't have write priviledges.

Regards, Geo
0
mi6agentAuthor Commented:
> perhaps the file you wanted is on a Network share and you do not have the privileges to access it?

That was my thought at first DragonSlayer - then i realized, i am not on a network, am logged in as administrator (Win2000) and i'm using FAT32 - so privileges should not be an issue.

The pathandfilename is set to a normal path and filename type - ie: c:\test\testfile.txt

any help or pointers are welcomed
0
DragonSlayerCommented:
Here are the error code listing http://support.microsoft.com/kb/q155011/

And your error (if you got the right one, that is) is definitely network related... strange...
0
mi6agentAuthor Commented:
Very strange.  The error "A write fault occurred on the network" seems odd when i'm not on a network or even trying to write/read from a networked system - it's all local.

0
mi6agentAuthor Commented:
just thought of something - maybe i'm at fault somewhere.

i've edited the code a bit but here is the code and how to see the error.

var
fhandle : THandle;
begin
fhandle:=CreateFile(PChar(pathandfilename),
                        GENERIC_READ or GENERIC_WRITE,
                        FILE_SHARE_READ or FILE_SHARE_WRITE,
                        nil,
                        CREATE_NEW,
                        FILE_ATTRIBUTE_NORMAL,
                        0);

Showmessage('Handle Returned = ' + IntTostr(fHandle) + ' -  LastError = ' + GetLastError);

    <== On first run of code - Message will show:  Handle Returned = 88 - LastError = 0
    <== On second run of code - Message will show:  Handle Returned = really large number - LastError = 80

I expect the LastError values but the "Handle Returned" values?  Are these correct or as i thought, errors.


if fhandle=INVALID_HANDLE_VALUE  <== flag error else continue
0
mokuleCommented:
??? So You don't receive ERROR_NET_WRITE_FAULT
0
mi6agentAuthor Commented:
yes - on the first run of the code the handle returned is 88 (ERROR_NET_WRITE_FAULT)

or have i got the wrong end of the stick with the createfile function?
0
mokuleCommented:
???
I can't see it here.
You've got Handle Returned = 88

    <== On first run of code - Message will show:  Handle Returned = 88 - LastError = 0
    <== On second run of code - Message will show:  Handle Returned = really large number - LastError = 80
0
mi6agentAuthor Commented:
http://msdn.microsoft.com/library/default.asp?url=/library/en-us/debug/base/system_error_codes__500-999_.asp

Code 88 =  A write fault occurred on the network. ERROR_NET_WRITE_FAULT

<== On first run of code - Message will show:  Handle Returned = 88 <== Error?
0
mokuleCommented:
You've received Handle 88. It is not an error code !!
0
mokuleCommented:
In my previous code there were errors.
Should be like this

procedure TForm1.Button1Click(Sender: TObject);
var
      fHandle: THandle;
      Filename: string;
      nWritten: cardinal;
      nWrite: cardinal;
      buffer: string;
begin
    Filename := 'C:\test.txt';
    fHandle := CreateFile(PChar(Filename),GENERIC_READ or GENERIC_WRITE,  FILE_SHARE_READ or FILE_SHARE_WRITE, nil, OPEN_ALWAYS, 0, 0);
    if fHandle <> INVALID_HANDLE_VALUE then
      begin
      buffer := 'something';
      nWrite := Length(buffer);
      WriteFile(fHandle,PChar(buffer)^, nWrite, nWritten, nil);
      CloseHandle(fHandle);
      Edit1.Text := 'OK';
      end
    else
      Edit1.Text := IntToStr(getlasterror);
end;
0
mi6agentAuthor Commented:
ok, let me play around with this a bit more.  I'll get back to you soon.

thanks for the help - appreciated :)
0
geobulCommented:
A possible cause could be that file is already opened EXLUSIVELY by other app.
0
geobulCommented:
On your second attempt (using CREATE_NEW) everything is OK.
- First run without error and the file was created.
- Second run : error 80 (file already exists) and INVALID_HANDLE_VALUE returned in fhandle (that really large number).

Regards, Geo
0

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
DragonSlayerCommented:
duh...
0
mi6agentAuthor Commented:
geobul is right...
and yep, i heard myself say "duh!" when i realised i made a mistake.

i'm going to split the points between mokule & geobul if that is ok with everyone?

i'll wait a day to see if anyone objects - just making sure that i am being fair :)
0
mi6agentAuthor Commented:
thanks again to all
0
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
Delphi

From novice to tech pro — start learning today.

Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.