How to get the file size given a path?

后端 未结 10 1164
自闭症患者
自闭症患者 2020-11-30 20:22

I have a path to file contained in an NSString. Is there a method to get its file size?

相关标签:
10条回答
  • 2020-11-30 20:41

    If you want only file size with bytes just use,

    unsigned long long fileSize = [[[NSFileManager defaultManager] attributesOfItemAtPath:yourAssetPath error:nil] fileSize];
    

    NSByteCountFormatter string conversion of filesize (from Bytes) with precise KB, MB, GB ... Its returns like 120 MB or 120 KB

    NSError *error = nil;
    NSDictionary *attrs = [[NSFileManager defaultManager] attributesOfItemAtPath:yourAssetPath error:&error];
    if (attrs) {
        NSString *string = [NSByteCountFormatter stringFromByteCount:fileSize countStyle:NSByteCountFormatterCountStyleBinary];
        NSLog(@"%@", string);
    }
    
    0 讨论(0)
  • 2020-11-30 20:42

    CPU raises with attributesOfItemAtPath:error:
    You should use stat.

    #import <sys/stat.h>
    
    struct stat stat1;
    if( stat([inFilePath fileSystemRepresentation], &stat1) ) {
          // something is wrong
    }
    long long size = stat1.st_size;
    printf("Size: %lld\n", stat1.st_size);
    
    0 讨论(0)
  • 2020-11-30 20:42

    It will give File size in Byte...

    uint64_t fileSize = [[[NSFileManager defaultManager] attributesOfItemAtPath:_filePath error:nil] fileSize];
    
    0 讨论(0)
  • 2020-11-30 20:49

    In case some one needs a Swift version:

    let attr: NSDictionary = try! NSFileManager.defaultManager().attributesOfItemAtPath(path)
    print(attr.fileSize())
    
    0 讨论(0)
  • 2020-11-30 20:50

    Bear in mind that fileAttributesAtPath:traverseLink: is deprecated as of Mac OS X v10.5. Use attributesOfItemAtPath:error: instead, described at the same URL thesamet mentions.

    With the caveat that I'm an Objective-C newbie, and I'm ignoring errors that might occur in calling attributesOfItemAtPath:error:, you can do the following:

    NSString *yourPath = @"Whatever.txt";
    NSFileManager *man = [NSFileManager defaultManager];
    NSDictionary *attrs = [man attributesOfItemAtPath: yourPath error: NULL];
    UInt32 result = [attrs fileSize];
    
    0 讨论(0)
  • 2020-11-30 20:54

    Following the answer from Oded Ben Dov, I would rather use an object here:

    NSNumber * mySize = [NSNumber numberWithUnsignedLongLong:[[[NSFileManager defaultManager] attributesOfItemAtPath:someFilePath error:nil] fileSize]];
    
    0 讨论(0)
提交回复
热议问题