Question

can't open in use file even for reading

Asked by: hibbidiji

I'm using the following function to mimic the tail command in unix.   It needs to open a file and read from it.  As you can see I'm only opening it in readonly mode but I still get the error that I cannot access the file.   Can anyone suggest an alternate method to accomplish this task?  

function tform1.Tail(FileName:string; Position:Integer):string;
var
  S: TStream;
  C: Char;
  L: Integer;
begin
  S := TFileStream.Create(FileName, fmOpenRead ,fmShareDenyNone);
  try
    S.Seek(Position, soBeginning);
    L := S.Size-Position;
    SetLength(Result, L);
    S.Read(Result[1], L);
  finally
    S.Free;
  end;
end;


Thanks!

This Question has been solved and asker verified All Experts Exchange premium technology solutions are available to subscription members.

Subscribe now for full access to Experts Exchange and get

Instant Access to this Solution

  • Plus...
  • 30 Day FREE access, no risk, no obligation
  • Collaborate with the world's top tech experts
  • Unlimited access to our exclusive solution database
  • Never be left without tech help again

Subscribe Now

Asked On
2006-11-29 at 09:06:50ID22076583
Tags

file

,

open

Topic

Delphi Programming

Participating Experts
1
Points
250
Comments
26

Trusted by hundreds of thousands everyday for fast, accurate and reliable tech support.

  • "The time we save is the biggest benefit of Experts Exchange to Warner Bros. What could take multiple guys 2 hours or more each to find is accessed in around 15 minutes on Experts Exchange." Mike Kapnisakis, Warner Bros.
  • "Our team likes having a resource that is more secure than just using Google and most experts using this service really know their stuff. It's nice to look here first versus using Google." Dayna Sellner, Lockheed Martin
  • "Anytime that I've been stumped with a problem, 9 out of 10 times Experts Exchange has either the accepted solution or an open discussion of the potential solution to the problem." Kenny Red, eBay Inc.

See what Experts Exchange can do for you.

Got a question?

We've got the answer.

Experts Exchange has been collecting answers to technology questions since 1996…3 million and counting! If you have a question, chances are we already have your answer.

Screenshot of Experts Exchange Knowledgebase

Need individual assistance?

Our experts are ready to help.

If you can't find the exact answer you're looking for, ask our exclusive community of 50,000 experts. You’ll get a personalized answer from a trusted professional.

Screenshot of Experts Exchange Knowledgebase

Want to learn from the best?

Read articles from industry experts.

Thousands of free tech tips, tricks, how-to’s and tutorials are available in our peer reviewed articles section. See for yourself how smart our experts are, no login required.

Screenshot of an Article

Working on a long term project?

Store your work and research.

Save solutions to your questions, answers you’ve discovered through searching plus helpful articles in your personal knowledgebase for easy future access.

Screenshot of Experts Exchange Knowledgebase

Access the answers to your technology questions today.

Subscribe Now

30-day free trial. Register in 60 seconds.

What Makes Experts Exchange Unique?

Members of the expert community talk about why the experience at Experts Exchange is different than what you will find anywhere else.

Trusted by the world's most respected brands.

image of each brand's logo

Faithfully serving IT professionals since 1996.

Experts Exchange Logo

Try it out and discover for yourself.

Subscribe Now

30-day free trial. Register in 60 seconds.

Related Solutions

  1. Printing with TStream
    How can I send a file to a printer using TStream objects(TFileStream, THandleStream...) ?
  2. tail c code
    Where can I find c code for the UNIX 'tail' command? Or something that works the same as 'tail -f'? Thanks!
  3. Icon and TStream
    Hi, It's the first time I'm using TStream. I got an error when I try to save the Icon part of my object. Find here below the code sample to help you to understand better... Thank you in advance Bob type TStartOptions = (soSW_SHOW, soSW_SHOWNORMAL); {********************...
  4. Bitmap and TStream ... a Q for Madshi
    Madshi, referencing another question that you provided and answer for Date: Sunday, February 06 2000 - 10:32PM PST Delphi : Q.10291114 From: baudewyns Title: "Icon and TStream How can I , or if it is possible to adapt the Icon and TStream program to a Bitmap and T...
  5. TStream
    Hi! My application downloads text from the internet into a TStream. How can I run though the TStream line by line (I need to do an IF statment on each line). Thanks for your help in advance, Graeme Sandwell graeme@officedevil.co.uk

Free Tech Articles

  1. WARNING: 5 Reasons why you should NEVER fix a computer for free.
    It is in our nature to love the puzzle. We are obsessed. The lot of us. We love puzzles. We love the challenge. We thrive on finding the answer. We hate disarray. It bothers us deep in our soul. W...
  2. SCCM OSD Basic troubleshooting
    SCCM 2007 OSD is a fantastic way to deploy operating systems, however, like most things SCCM issues can sometimes be difficult to resolve due to the sheer volume of logs to sift through and the dispe...
  3. Migrate Small Business Server 2003 to Exchange 2010 and Windows 2008 R2
    This guide is intended to provide step by step instructions on how to migrate from Small Business Server 2003 to Windows 2008 R2 with Exchange 2010. For this migration to work you will need the fo...
  4. Create a Win7 Gadget
    This article shows you how to create a simple "Gadget" -- a sort of mini-application supported by Windows 7 and Vista. Gadgets can be dropped anywhere on the desktop to provide instant information, ...
  5. Outlook continually prompting for username and password
    There have been a lot of questions recently regarding Outlook prompting for a username and password whilst using Exchange 2007. There are a few reasons why this would happen and I will try to cover t...
  6. Backup Exchange 2010 Information Store using Windows Backup
    There seems to be quite a lot of confusion around the ability to backup Exchange 2010 using the built in Windows Backup feature. This stems from the omission of this feature prior to Exchange 2007 s...

Cloud Class Webinars

  1. Avoiding Bugs in Microsoft Access
    Alison Balter takes and in-depth look at avoiding bugs in Access. In this webinar you will learn about using the immediate window to debug your applications, invoking the debugger, using breakpoints to troubleshoot, stepping through code, setting the next statement to execute, ...
  2. Top 10 Best New Features in Visio 2010
    Scott Helmers gives live demonstrations of the top 10 new features in Visio 2010. This webinar will teach you how to create compelling diagrams by adding shapes to the page with a single click, linking the shapes in a diagram to data in Excel (or SQL Server, or SharePoint), ...
  3. IT Consultant Business Secrets Revealed
    Michael Munger, Experts Exchange tech pro and IT consultant, pulls back the curtain on his very successful businesses and answers question on every IT consultant and business owner should know about. He shares secrets on what he did to solve the 5 most common problems in IT, ...
  4. Disaster Recovery and Business Continuity
    Quest CTO, Mike Billon, gives an overview of the steps involved in building a dunamic disaster recovery plan. Through case studies and an examination of software/hardware tooles for monitoring and testing, you'll gain a better understandin of where you are, where you want ...
  5. Organize Your Visio Diagrams with Containers and Lists
    Scott Helmers uses cross functional flowcharts, wireframe diagrams, data graphic legends and seating charts to teach you: how to ustilize all three new structured diagram components in Visio 2010, the best practices for organizeing shapes in previous version of Visio, how to organize ...
  6. How to Us Objects, Properties, Events and Methods in Microsoft Access
    Alison Dalter gives an in-depbth look at objects, properties, events and methods in Microsoft Access. In this webinar you will learn about using the object browser, referring to objects, working with properties and methods, working with object variables, understanding the ...

Join the Community

Give a Little. Get a Lot.

Join the community of experts here and help other tech pros by answering question in your area of expertise. You can earn FREE access to all Experts Exchange's premium features and resources.

Join the Community

Answers

 

by: kretzschmarPosted on 2006-11-29 at 09:22:03ID: 18038651

it could be that another process did open this file exclusive
-> no chance to read it by your process

 

by: hibbidijiPosted on 2006-11-29 at 09:34:44ID: 18038778

Hiya Michael!
How about workarounds?   Executing a file copy then reading that temp file?   Anything else you can think of?
Thanks!

 

by: kretzschmarPosted on 2006-11-29 at 09:42:30ID: 18038852

>Executing a file copy then reading that temp file?  
if you can copy it, then you should it also read it.

do a test, then we look further

btw. a similar q was here one/two years ago,
i will search it, maybe this solution is useable for u

meikl ;-)

 

by: hibbidijiPosted on 2006-11-29 at 09:48:46ID: 18038902

When using a shell copy function I can indeed copy the file, though my own internal functions seem to be keeping ahold of the file  - I'm sure I can chase that down though.  Here is my copy file function using shellapi
function scShellCopyFile(FormHandle : THandle; StrFrom, StrTo : string; BlnSilent : Boolean = False) : Boolean;
var
  F : TShFileOpStruct;
begin
  F.Wnd:=FormHandle;
  F.wFunc:=FO_COPY;
  F.pFrom:=PChar(StrFrom+#0);
  F.pTo:=PChar(StrTo+#0);
  F.fFlags := FOF_ALLOWUNDO or FOF_RENAMEONCOLLISION;
  if BlnSilent then
    F.fFlags := F.fFlags or FOF_SILENT;
  if ShFileOperation(F) <> 0 then
    result:=False
  else
    result:=True;
end;

 

by: kretzschmarPosted on 2006-11-29 at 09:48:59ID: 18038905

hmm, the other solution is exactly what you posted,
guess you got it from here :-))


can you copy the file?

meikl ;-)

 

by: hibbidijiPosted on 2006-11-29 at 09:53:05ID: 18038936

I found that I had an open filemap handle on the file and killed it - this let go of my file so I could mess about with the temp file.   I suppose the only question would be should the shell be able to copy a file yet delphi not be able to read it (readonly).  I have my solution to a point - it will work though it's a little roundabout.   Any other ideas do you think?

 

by: hibbidijiPosted on 2006-11-29 at 09:53:53ID: 18038942

Sorry for the cross post-  looks like this is the solution.   Thanks for pointing me at the untouchable file and have a great day.

 

by: kretzschmarPosted on 2006-11-29 at 09:54:10ID: 18038945

ok, didn't see your last comment before my last post

so it should be possible to read from the file

this kind of streamcreation i never used (seems to be a overloaded method)
  S := TFileStream.Create(FileName, fmOpenRead ,fmShareDenyNone);

maybe it makes a differentce if u use
  S := TFileStream.Create(FileName, fmOpenRead or fmShareDenyNone);

a copy and then a read makes not much sense, if the file is huge,
but of course on smaller files it may be a workaround

meikl ;-)

 

by: hibbidijiPosted on 2006-11-29 at 09:55:30ID: 18038958

trying your solution now - will request a change if we get it fixed with your method

 

by: kretzschmarPosted on 2006-11-29 at 09:56:19ID: 18038967

hups,

we are both really active at same time.
well, it is solved for you,
then i could paq this q and refund your points
with my role as Page Editor

meikl ;-)

 

by: kretzschmarPosted on 2006-11-29 at 09:58:02ID: 18038974

puh, seems i am too slow :-))

 

by: hibbidijiPosted on 2006-11-29 at 10:00:06ID: 18038998

I'll see how my read goes with your code - this might be really helpful if it does help and I'm not worried on the points :)  I'll let you know what I come up with.  it's definitely different with the OR.  it appears to be freezing now - though that could just be the file scan.

 

by: kretzschmarPosted on 2006-11-29 at 10:01:42ID: 18039013

let me know, if i should reopen this question

if u use a memory maped file, then there may more possibilities,
but then i need more information and time to try

meikl ;-)

 

by: kretzschmarPosted on 2006-11-29 at 10:03:12ID: 18039025

ok, keep me informed

(just again: see your last comment not, before posting)

meikl ;-)

 

by: hibbidijiPosted on 2006-11-29 at 10:17:05ID: 18039138

Alright,
When using your OR operator for that open action, I do not get the error that the file is in use at all.   My biggest problem seems to be in this function now.  It is supposed to open the file and count the number of characters in it. The files I'm dealing with are fairly small - under 10mb in general - and when run on an unlocked file it takes less than 2 seconds.  

When running this function on my locked file, it returns -1 instead of the correct number of characters.

Any idea why? I believe it's related to the question's original issue

note that in the following function I've also tried the flag FILE_FLAG_RANDOM_ACCESS in the createfile.


function GetFileLengthInCharacters(filename:string):integer;
var
filesize:integer;
FileHandle:tHandle;
CharCounter:integer;
begin


 FileHandle := CreateFile(pansichar(FileName), GENERIC_READ, FILE_SHARE_READ, nil, OPEN_EXISTING, FILE_FLAG_SEQUENTIAL_SCAN, 0);
 CharCounter := GetFileSize(FileHandle, nil);
 fileclose(filehandle);
 result := charcounter;

end;

 

by: kretzschmarPosted on 2006-11-29 at 10:38:43ID: 18039314

?? would not be the charcount the filsize -1
(the filesize could be retrieved with the findfirst-api without open the file)

explain a bit more

meikl ;-)

 

by: hibbidijiPosted on 2006-11-29 at 10:49:24ID: 18039411

Perhaps I'm amiss here in that I misunderstood something that another programmer did because of his var names.   As I look now it does look like this is a roundabout way of doing it.   How would you rewrite the function to return the filesize?  What do you think the best way would be.

Remember that the output of this function should return a value that would be appropriate to the input of the tail function in my first post.  

thank you.

 

by: kretzschmarPosted on 2006-11-29 at 11:13:19ID: 18039606

maybe this way (not tested, just from head)

function getsize(APathFileName : String) : Integer;
var SRec : TSearchrec;
begin
  result := 0;
  try
    if findfirst(APathFileName, faAnyFile, SRec) > 0 then
      result := srec.Size;
  finally
    findclose(srec);
  end;
end;

meikl ;-)

 

by: hibbidijiPosted on 2006-11-29 at 11:34:40ID: 18039787

Yikes,
No luck.  Here's the status.

if I copy off a backup of the file, get the length, then use that for the input in the tail function, it DOES return data properly. This implies that the filestream that tail uses is good and it IS reading the file properly using that method.

The first method I used returns properly on the backup (unlocked) file and -1 on the locked file.

The findfirst method you pasted returns 0.  I modified it to return the actual return value (checking for a -1 or other errorcode but it's actually returning 0.  This would imply that it's not finding the file, I would assume.  However, i've been using the same var and value for the file as in the tail function so I can assume that it is indeed valid.   A caveat here is that the file I'm working with is on a UNC path i.e. \\domain\server\folder\file.txt

I did not find anything that states that UNC paths are not valid when using findfirst.

Any more ideas?  I CAN go back to copying to a temp file but it's obviously not the ideal solution.

 

by: kretzschmarPosted on 2006-11-29 at 12:01:13ID: 18040035

too late for me today to look deeper into your problem,
do you have a chance to change the "writer-process"?

until tomorrow (from my point)

meikl ;-)

 

by: hibbidijiPosted on 2006-12-01 at 08:52:23ID: 18054960

Back.
Sorry for the delay!
I never did get it to read from the file.  This is odd for a couple reasons:

windows can copy it without unlocking it
text editors can read from it without unlocking it

findfirst is still returning 0 (file not found) though the same var, which contains the path to the filename, can be used to copy the file with no issues.  the path is correct but findfirst just isn't working.

I'm about ready to give up and go with the file backup / read / etc method.  It's just frustrating because I know the file CAN be read - text editors are doing it.  I would just like to know why delphi isnt.

Ho hum

 

by: kretzschmarPosted on 2006-12-01 at 09:14:56ID: 18055135

well, then it should possible with delphi also

did you simple tried to read it into a richedit?
just with
richedit1.lines.loadfromfile(FileName);
?

of course just as test, not as solution

meikl ;-)

 

by: hibbidijiPosted on 2006-12-01 at 14:07:53ID: 18057034

No dice.
I still get the following error when trying the loadfromfile

First chance exception at $7C812A5B. Exception class EFOpenError with message 'Cannot open file "\\server\file.txt". The process cannot access the file because it is being used by another process'. Process Project1.exe (2312)

I will repeat for clarity that I can, every time, open the file in notepad, notepad++, word and copy it through explorer

This is perplexing isn't it?

 

by: hibbidijiPosted on 2006-12-01 at 14:16:39ID: 18057070

to save possible time and confusion it should be noted that I replaced my actual filename and path with the \\server\file.txt

 

by: hibbidijiPosted on 2006-12-01 at 14:51:36ID: 18057243

Last (for today at least)
I wrote up a function in C++ that I would use to read the filesize but it ALSO returns -1:

void __fastcall TForm1::Button1Click(TObject *Sender)
{

   FILE *fp;
   int letter;

   if((fp = fopen("\\server\file.txt", "r")) == NULL)
   {
DWORD dwSizeLo, dwSizeHi;
dwSizeLo = GetFileSize ( fp, &dwSizeHi);
char buffer[35];
String mysize = ltoa(dwSizeLo, buffer, 10);
lbl->Caption = mysize;
   }

   fclose(fp);

}



No luck with this either.  This is really perplexing!

 

by: kretzschmarPosted on 2006-12-01 at 23:06:32ID: 18058936

>This is really perplexing!
thats true

i will try to setup a similar case

meikl ;-)

20120131-EE-VQP-002

3 Ways to Join

30-Day Free Trial

The Experts

98% positive feedback on 31,087 answers since March 2000. angeliii is a Microsoft Most Valuable Professional for his work with MS SQL Server & Develoment.

He has also proven his knowledge of Visual Basic Programming, PHP Scripting and Oracle Databases.

The Experts

97% positive feedback on 10,752 answers since July 2000. lrmoore has more than 18 years experience in the networking industry.

The six-time Mircosoft MVPs specialties include firewalls, virtual private networking, and network management.

Testimonials

"...and excellent source for support... Kind of like having your very own IT dept." Electriciansnet

Testimonials

"I was apprehensive at signing up at first. However... it has already made my life as an IT administrator much easier." JaCrews

Testimonials

"WOW! You guys have great, active, and knowledgeable people on here." moore50

Business Clients

Business Clients

In the Press

"If you’ve got a question... Experts Exchange can supply an answer.”

In the Press

"...an invaluable aid for both IT professionals and those who require tech support."

In the Press

"where IT professionals provide quick answers on just about any topic"

Business Account Plans

Loading Advertisement...