How can i get my file size in Objective-C -
after search did not find problem:
nsstring *path = @"~/desktop/folder/"; pathg = [path stringbyexpandtitlepath]; nsfilemanager *fm = [nsfilemanager defaultmanager]; nsarray *array = [fm contentsofdirectoryatpath: path error: null]; for(int = 0; < array.count; ++i) { nsfilesize *num = [array[i] filesize]; }
error: use of undeclared identifier 'num'
if need file size of single file, can constructing file url , querying url's attributes directly.
nsstring *filepath = [@"~/.bash_history" stringbyexpandingtildeinpath]; nsurl *fileurl = [nsurl fileurlwithpath:filepath]; nsnumber *filesizevalue = nil; nserror *filesizeerror = nil; [fileurl getresourcevalue:&filesizevalue forkey:nsurlfilesizekey error:&filesizeerror]; if (filesizevalue) { nslog(@"value %@ %@", fileurl, filesizevalue); } else { nslog(@"error getting size url %@ error %@", fileurl, filesizeerror); }
if need iterate contents of directory, in question, can url based version way in question. using contentsofdirectoryatpath:...
returns array of file names nsstring
s, , have rebuild full path , attributes additional step:
nsstring *directorypath = [@"~" stringbyexpandingtildeinpath]; nsfilemanager *fm = [nsfilemanager defaultmanager]; nsarray *array = [fm contentsofdirectoryatpath: directorypath error:null]; (nsstring *filename in array) { nserror *attributeserror = nil; nsdictionary *attributes = [fm attributesofitematpath:[directorypath stringbyappendingpathcomponent:filename] error:&attributeserror]; unsigned long long size = [attributes filesize]; //note isn't pointer nslog(@"%llu", size); }
you can make similar solution using file urls:
nsstring *directorypath = [@"~" stringbyexpandingtildeinpath]; nsurl *directoryurl = [nsurl fileurlwithpath:directorypath isdirectory:yes]; nsfilemanager *fm = [nsfilemanager defaultmanager]; nserror *contentserror = nil; nsarray *contents = [fm contentsofdirectoryaturl:directoryurl includingpropertiesforkeys:@[nsurlfilesizekey, nsurlisdirectorykey] options:0 error:&contentserror]; if (contents) { (nsurl *contenturl in contents) { nserror *isdirectoryerror = nil; nsnumber *isdirectorynumber = nil; [contenturl getresourcevalue:&isdirectorynumber forkey:nsurlisdirectorykey error:&isdirectoryerror]; if (isdirectorynumber) { if (![isdirectorynumber boolvalue]) { nsnumber *filesizenumber = nil; nserror *sizeerror = nil; [contenturl getresourcevalue:&filesizenumber forkey:nsurlfilesizekey error:&sizeerror]; if (filesizenumber) { nsinteger size = [filesizenumber integervalue]; nslog(@"%li", (long)size); } else { nslog(@"error getting file size file %@ error:%@",contenturl,sizeerror); } } } else { nslog(@"error getting url %@ directory: %@", contenturl, isdirectoryerror); } } } else { nslog(@"error getting contents directory %@ error: %@", directoryurl, contentserror); }
Comments
Post a Comment