yokks
yokks

Reputation: 5773

getting the size of the file contents in iphone

Am writing an application for iphone to read a text file using NSData.

NSFileHandle *fileRead;

// this may lead to crash or memory issue, if the file size is about 10 mb or more

NSData *data =   [fileRead readDataOfLength:(entire contents of the file)]; 

For example, if the file size is 8 kb, we can reading it in 8 iterations by 1kb per cycle.

Before reading the file, how can we find the size of the file contents.so that we can write the code in a optimized way to read the file effectively?

plz give me your suggestions....

Upvotes: 1

Views: 484

Answers (2)

Anomie
Anomie

Reputation: 94794

If you're really wanting to read the entire file, just use readDataToEndOfFile and don't worry about determining the length beforehand.

From an NSFileHandle, you can find the length by first seekToEndOfFile and then offsetInFile. If you have the actual file name, you could use NSFileManager's attributesOfItemAtPath:error: to retrieve the length (as with C's stat) instead. Or, for that matter, you could actually use stat, or fstat on the file descriptor returned by NSFileHandle's fileDescriptor method.

Upvotes: 2

fieldtensor
fieldtensor

Reputation: 4050

The iPhone has all of the standard POSIX APIs, so you can use stat("file.txt", &st), where st is a "struct stat". The "st.st_size" member will give you the file size in bytes.

Upvotes: 2

Related Questions