I am just wanting to know how offsetInFile works? and what is the difference between seekToFileOffSet. and code examples you know of would be helpfull as well :)
Asked
Active
Viewed 1,315 times
1
-
This question will be closed as it is not a specific code related question, but a discussion. – coneybeare Jun 14 '11 at 21:09
1 Answers
4
For standard file descriptors, -[NSFileHandle offsetInFile]
and -seekToFileOffset:
have straightforward POSIX equivalents:
[handle offsetInFile];
=> off_t offset = lseek([handle fileDescriptor], 0, SEEK_CUR);
[handle seekToFileOffset:off];
=> off_t offset = lseek([handle fileDescriptor], off, SEEK_SET);
The difference between them is that the first returns the current offset, while the second changes the offset.

Jeremy W. Sherman
- 35,901
- 5
- 77
- 111
-
ah right, and when you say returns offset, is the offset a position in the file? what I am trying to do is open up a file that has say 1000 lines in it and pull a single line from the file based on the number a user enters... am I going down the right track in order to do this? – tinhead Jun 14 '11 at 22:35
-
The file offset won't be much help to you unless the file has fixed-width lines, like a punchcard. Instead, you'd have to scan the file for newline characters and then save out the characters for the line in question into a buffer. – Jeremy W. Sherman Jun 14 '11 at 22:37
-
-
If seekToFileOffset allows you to change the offset can you then return the characters that are located in that offset? – tinhead Jun 14 '11 at 23:16
-
Yes. The file offset is implicitly used when reading bytes from the file; if you issued `read(fd, buf, count)`, the `count` bytes read would be those in the range `(offset, count)`. The `NSFileHandle` equivalent for the POSIX `read` call would be `[handle readDataOfLength:count]`. – Jeremy W. Sherman Jun 14 '11 at 23:28
-
Don't forget to include the newline character in the line length when calculating the offset. To skip `"12345\n"`, you need to skip 6 characters (5 + newline), not 5. – Jeremy W. Sherman Jun 14 '11 at 23:28
-
okay cool, thanks for the information I will have to do more research from this, but you have at least given my more detail to further my investigation. Thank you for your help :) – tinhead Jun 14 '11 at 23:31
-
Just another thing to consider, if you happen to have multibyte characters they may trip you up. – axiixc Jun 15 '11 at 03:04