lseek( ) on file opened with O_APPEND

  • Permalink
  • submit to reddit
  • Email
  • Follow


I noticed that when I opened a file using open( ) with the O_APPEND
flag that I have to
first write to the file in order to have lseek( ) return the offset
value equivalent to the offset
from the beginning of the file.  For example, the code below

    fd = open( my_file, O_APPEND | O_WRONLY );
    printf( "Current offset following lseek( fd, O, SEEK_CUR): %d\n",
        ( int ) lseek( fd, 0, SEEK_CUR ) );

will print the text

Current offset following lseek( fd, O, SEEK_CUR): 0

If I write to the file and then call lseek( fd, 0, SEEK_CUR ), I will
get the actual offset from
the beginning of the file

    fd = open( my_file, O_APPEND | O_WRONLY );
    printf( "Current offset following lseek( fd, O, SEEK_CUR): %d\n",
        ( int ) lseek( fd, 0, SEEK_CUR ) );
    bytes_written = write( fd, buffer, num_bytes );
    init_off = lseek( fd, 0, SEEK_CUR ) - (off_t ) bytes_written;
    printf( "Actual initial offset to end of file: %d\n", init_off );
    printf( "Current file offset: %d\n", ( int ) lseek( fd, 0,
SEEK_CUR ) );

will give me output 
 
Current offset following lseek( fd, 0, SEEK_CUR): 0
Actual initial offset to end of file: 12
Current file offset: 23  

Note that this suggests that the initial file size was 12 bytes, and
11 bytes were written to
fd.

In summary, lseek( fd, 0, SEEK_CUR ) will return (off_t ) 0 after a
file is opened for
appending.  Once at least one byte is written to fd, lseek( fd, 0,
SEEK_CUR ) will
return the offset from the beginning of the file.  Is there a better
way to get the offset to
the end of the file?  I could have opened the file without the
O_APPEND flag, and called
lseek( fd, 0, SEEK_END ), but this not safe if multiple processes are
appending to the same
file.  By the way, forgive my lack of error checking above; I have
omitted it for the sake of
clarity in this post, not in the code itself.

Thanks for your help,
Victor
0
Reply weinstev 11/18/2003 7:55:37 PM

See related articles to this posting


In article <4c9cde18.0311181155.3a092f44@posting.google.com>,
Victor <weinstev@yahoo.com> wrote:
>In summary, lseek( fd, 0, SEEK_CUR ) will return (off_t ) 0 after a
>file is opened for
>appending.  Once at least one byte is written to fd, lseek( fd, 0,
>SEEK_CUR ) will
>return the offset from the beginning of the file.  

O_APPEND causes you to go to the end immediately before writing anything.
Until you try to write something, it doesn't have to reposition.

>						    Is there a better
>way to get the offset to
>the end of the file?  

Call fstat().

>		       I could have opened the file without the
>O_APPEND flag, and called
>lseek( fd, 0, SEEK_END ), but this not safe if multiple processes are
>appending to the same
>file.

If other processes are appending to the file, any method you use is
useless, since the file length can change after you call it.

-- 
Barry Margolin, barry.margolin@level3.com
Level(3), Woburn, MA
*** DON'T SEND TECHNICAL QUESTIONS DIRECTLY TO ME, post them to newsgroups.
Please DON'T copy followups to me -- I'll assume it wasn't posted to the group.
0
Reply Barry 11/18/2003 8:53:40 PM
comp.unix.programmer 10672 articles. 64 followers. Post

1 Replies
1054 Views

Similar Articles

[PageSpeed] 39


  • Permalink
  • submit to reddit
  • Email
  • Follow


Reply:

Similar Artilces:

File::open and File.open
What exactly is the difference between these? :: is a class method while is an instance method??? If that is so, could someone clarify this with more detail? I use File.open, but File::open works too. However sometimes, this is not the case which adds to my confusion :) For example, I can only do Digest::MD5.new() and not Digest.MD5.new() why is that? I don't fully understand OO programming... perhaps this is my problem. Thank you for your time. -- Posted via http://www.ruby-forum.com/. Robert Klemme schrieb: > Brad Tilley wrote: >> What exactly is the difference betwe...

Open folder, read file, close file, open new folder, read file close file etc....
Hello, My current directory has several folders within it. Each folder has the same type of file within it. How do i go from the current directory, into one of the folders, edit the file, then come out of the folder, then go into another folder, edit a file then come out of the folder then into a new one etc etc etc. If this does not make sense i apologise and will try to explain my problem a little better. Any help would be much appreciated. Cheers, Phil Phil: I'm not sure it makes sense. Personally I use the mouse and keyboard for doing this. Were you thinking of something else?...

Acroread does not open files
I've had this problem on two different installations of Linux. Acroread would not open PDF files, not from a command line, nor as a Mozilla plug-in. It would give the following message: "There was an error opening this document. A temporary file could not be opened." The solution was very simple for me: DEBUG USING strace ================== bash (I normally use tcsh) strace acroread filename.pdf > output.txt 2>&1 in the file, a line lstat64("/home/username/tmp/AcroaRKu9Y", 0xbfffddf0) = -1 ENOENT (No such file or directory) points to the loc...

Determine number of open files and/or open file locks
Hello. I'm trying to debug some program running on HP-UX 11i. In the application log file, I got a lot of these messages: *** warning: fork: no more processes - retrying Well, it seems that something hit a limit here and I'm thinking that it might be the number of open files (nfile) and/or the number of open file locks (nflocks). Is there some way, that I can find out how many open files there are in the system and how many open file locks there are? Thanks a lot, Alexander Skwar -- panic("aha1740.c"); /* Goodbye */ 2.2.16 /usr/src/linux/drivers/scsi/aha1740.c ������...

How do I open a postscript file, like I open an excel file?
I'm trying to open a file that I saved as a .ps. I want to open it in the same maner as I open an excel file? To open an excel file, such as *.xls, you need Excel; to open a *.ps file, you need Ghostscript. It's free. You should be able to find it on internet. George Zou http://gtoolbox.yeah.net If you have trouble finding GhostView, postscript file opener for Windows, you can download it from here. http://www.cs.usyd.edu.au/~kap/General/Ghostview/ Charles. ...

Error 1 with Open File+.vi:Open File
Hallo ... ich arbeite mit LabVIEW 7 und habe ein Problem mit der Funktion "Datei �ffen". In einem umfangreichen Messprogramm lese ich zu Beginn mit Hilfe eines entwickelten VI Daten aus einer Datei. Wenn ich zu einem sp�teren Zeitpunkt nochmals Daten einlesen m�chte hat das VI das eben noch einwandfrei funktionierte Problem mit der Funktion "Datei �ffnen". Fehlermeldung: Fehler 1 ist bei Open File+.vi:Open File aufgetreten M�gliche Gr�nde: LabVIEW: Ein Ausgabeparameter ist ung�ltig. --- NI-488: Befehl erfordert, da� der GPIB-Regler der aktive Regler ist. Kann mir j...

where does open open the file?
I'm having problem reading from the beginning of a file. Here is the code (more or less) ifstream codefin; ofstream codefout; while (not_annoyed) { codefout.open("bar"); // write to bar, works fine codefout.bar(); system("command to change bar to foo"); codefin.open("foo"); if (!codefin.is_open()) cout<<"ERROR: couldn't open foo for reading"<<endl; cout<<codefin.tellg(); codefin.seekg(0,ios::beg); cout<<codefin.tellg(); if (codefin.eof()) cout<<&q...

&quot;Error 7 occurred at Open File +.vi:Open File&quot; when opening a newly built application
Hello, &nbsp; After successfully building a standalone application in LabView 7.1, I get this error when I try to run my .exe file.&nbsp; I don't think any files are supposed to open upon execution except for my top level VI, which appears to open just fine, so I'm unsure why this error pops up.&nbsp; Does anyone have any ideas that might help or has anyone run into this error&nbsp;before? &nbsp; Thanks in advance! &nbsp; Jason ...

why two file open operations when opening a file on a server share?
Hello, I am curious about the following protocol trace between an NT client and XP pro server: I open a word doc on the server's shared folder using MS Word on the NT client. Sniffing with ethereal, I see (each message simplified for brevity): client-> NT_CREATE_ANDX_REQUEST Path, MyFile.doc server-> NT_CREATE_ANDX_RESPONSE Fid: 0x000F client-> CLOSE_REQUEST 0x000F server-> CLOSE_RESPONSE client-> TRANS2_REQ MyFile.doc server-> TRANS2_RESPONSE MyFile.doc client-> NT_CREATE_ANDX_REQUEST Path, MyFile.doc server-> NT_CREATE_ANDX_RESPONSE Fid: 0x400...

error 7 open file+.vi when opening multiple csv files
&nbsp; &nbsp; <img style="WIDTH: 543px; HEIGHT: 385px" height="320 src= http://i67.photobucket.com/albums/h299/ghtokyo/csv_loop.jpg" width="456"> Hi, I it was interesting (and frustrating) that I, intermitantly, got the open file error #7 when I was sitting in a loop opening csv files using ReadFromSpreadsheet file.vi.&nbsp; The ReadFromSpreadsheetFile.vi is a higher level vi which should open the file, read the number of specified lines,&nbsp;then close the file afterwards.&nbsp; IT reads the csv files correctly for one iteration of the...

Difference between BINARY mode file opening and TEXT mode file opening
Hi, Can anyone please tell me the difference of opening file in Binary mode or in Text mode? On Sat, 23 Aug 2008 23:12:41 -0700 (PDT), manu <manumg007@gmail.com> wrote: >Hi, > >Can anyone please tell me the difference of opening file in Binary >mode or in Text mode? Are you perhaps taking the same class as subramanian100in? In either case, you can check the thread he (or she) started 8 hours earlier with the subject "text and binary streams". -- Remove del for email -----BEGIN PGP SIGNED MESSAGE----- Hash: SHA1 In any modern operating system I can think of...

file open
Hi all how do i get this new looking dialog to showup - the one like vo2.8's File, Open Project dialog seen loads of stuff on the newsgroup, but none that i can understand ... and no code (and i have tried a lot) that shows the five buttons on the left like recent docs etc. i MUST be able to a) restrict to folders only if needed b) remove / disable the "New Folder" button top right. regards richard Hello Richard, Try this: FileRequest("c:\", "Trial", "*.*", "") Include the Terminal Light Lib HTH Conrad ...

Open file with File Dialog
I know how to use the File Dialog control but I'm not sure how to actually open the file that is selected. Here's my code: 'Create a FileDialog object as a File Picker dialog box. Set fd = Application.FileDialog(msoFileDialogOpen) 'msoFileDialogFilePicker ' Select Excel file for import With fd If .Show = True Then .AllowMultiSelect = False 'Find the selected file name For Each varFile In .SelectedItems strFile = varFile Next Else MsgBox "Select a file." GoTo FindFile_Exit End If End With So once I have the name of...

Opening a file in File Manager
My applications (created with Sun Studio Fortran 95 under Solaris 8) create several plain, vanilla ASCII text files. When I view the directory in File Manager the icons for those text files are the interconnected gears, indicating a PID. When I double-click on the icons (wanting to view them with the screen editor) I do indeed get an error message indicating that I can't open them. Write-clicking on the icons doesn't give the option of opening the files. I *can* open the files from within the Screen Editor itself, but opening them from within File Manager is more convenient. How...

File Association
I am using windows 7 and Matlab 2011a. I have .m and .fig files associated with matlab however when I open one outside of matlab, the program opens however the .m or .fig file are not opened. I just get the home windows of Matlab. I tried the code below as I found on another thread with no luck. commandwindow; cwd=pwd; cd([matlabroot '\toolbox\matlab\winfun\private']); fileassoc('add','.fig') ;cd(cwd); disp('Changed Windows file association. FIG-files are now associated with MATLAB.') ...

Opening an already Opened file
HI all, I an designing an application in C++. i want to open file requested by end user but i want to reflect an error to user if file is already opened by some other application.. will anybody tell me that how to know that the file is already open or closed.. any help is highly appreciated... thanks, Munish Nayyar emanshu "IM" > I an designing an application in C++. i want to open file requested by > end user but i want to reflect an error to user if file is already > opened by some other application.. > will anybody tell me that how to know that the file is already...

Find files that are open and who has them open
We are running suse linux 9.1 as a file server with samba. My question is how to find files that are open by users, and if possible with samba one step further, to determine which workstation has it open. (We currently have one linux user on the server which redirects to the 15 windows workstations.) Thanks in advance. Matt On 2005-05-11, Matt_Schneider@peoplepc.com <Matt_Schneider@peoplepc.com> wrote: > is how to find files that are open by users fuser will tell, Also smbstatus. See the documentation of those two commands. Davide -- Trying to get Windows to run on the hardware ...

opening existing files with OPEN()
Hi, I am trying to write my own program where I am trying to read x,y,z points from an existing. The current beginning of my code has been working well so far, until a few hours ago, where it says that it can't find the existing files I'm telling it to find by name (even though I am spelling the names correctly and making sure that file is in the same directory). Here is my code. Any suggestions of where I can look? Thanks: ~~~~~~~~~~~~~~~~~~~~~~~~~~~~ implicit none double precision :: x_coord(100000), y_coord(100000), z_coord(100000), z_max, z_min integer :: i, j, openstatus, reads...

Error with Open file file
Hello, I have some problem while open file with spaces. Please advice me how to correct it. My Script: if {$filename eq {}} { set filename "[tk_getOpenFile -multiple 1 -filetypes $::pref (openTypeText)]" if { $filename eq {} } return ;# Cancel } set InputFile [open "$filename" r] Error generated by TCL: couldn't open "{D:/TroubleTicket/May/NA04500996-CallCompletionRatio/ InitialSymptoms/MSS16 090422/MSS16 090422.txt}": no such file or directory couldn't open "{D:/TroubleTicket/May/NA04500996-CallCompletionRatio/ InitialSymptoms/MSS16 09042...

Open Files and File Locking
What are the rules governing locking/sharing of open files? I.e., if I have a file open for writing in one process, will other processes be able to open the file as well? What type of access (read and/or write) would they have to it? What if the same process tries to open the file a second time? I'm relatively new to Linux/POSIX programming, so I'm not familiar with how these things work. <justin.olbrantz@gmail.com> wrote in message news:1136766357.089370.153510@z14g2000cwz.googlegroups.com... > What are the rules governing locking/sharing of open files? I.e., ...

alternate index file: How to know if an open file is an primary or a secondary file
Hello My application does not know the kind of file which the user asks it to open. With the Db.DB_UNKNOWN flag and the db.get_type() method, it is easy to know the underlying kind of database: DB_BTREE, DB_RECNO, DB_QUEUE or DB_HASH. But I am wondering how to know if DB_BTREE file is an primary btree or a secondary btree file??? The documentation of Db.open() and Db.get_type() specifies only these 4 values and it would help to know as soon as possible the underlying type of the btree database. Regards Francis ANDRE francis.andre@easynet.fr (Francis ANDRE) writes: ...

After write TDMS file, I close the storage ref (file), then I delete the file in program, error occured:File already open. How to solve it?
I want to delete channel groups in TDMS file, but the delete storage VI doesn't work, so I need to copy the needed datas to another file, and then delete the orignal file. The error occured&nbsp; when I deleted the orignal file, the prompt was: File already open. But I examined my program and I had used the colse storage VI to close the storage ref(file), the ref closed&nbsp;was&nbsp;equal to the ref open. How to solve it? &nbsp; Thanks for your reply! Untitled 1.vi: http://forums.ni.com/attachments/ni/170/266602/1/Untitled 1.vi The file connections are refcounted, so it...

How to open a logical partition and read all of its file using windows function ReadFile() ? Question How to open a logical partition and read all of its file using windows function ReadFile() ?
Hii In my application , wanna copy all files from one partition to another partition. First I copied a file that I taken default and copied to another partition. The above operation is done by using the control code "FSCTL_GET_RETRIEVAL_POINTERS". The clusters used are read and wrote into destination volume using readfile() and writefile() windows functions. Now I gotta copy all files..... So how to proceed ....?? Thanking you. On Sat, 13 Jun 2009 09:37:42 -0700 (PDT), krish <krishnampkkm@gmail.com> wrote: >Hii > >In my applicatio...

(DELETE-FILE open-file-stream)
How should DELETE-FILE behave on open file streams? <http://www.lisp.org/HyperSpec/Body/fun_delete-file.html>: If the filespec designator is an open stream, then filespec and the file associated with it are affected (if the file system permits), in which case filespec might be closed immediately, and the deletion might be immediate or delayed until filespec is explicitly closed, depending on the requirements of the file system. If *DEFAULT-PATHNAME-DEFAULTS* is set to something silly and the file which is actually to be deleted is differen...