我编写了一些方法,这些方法可以帮助我获得文件/文件夹的大小,并将结果转换为人类可读的字符串。问题是,当这个大小超过2.1GB时,返回的数字会更改为一个随机负数,如"-4324234423字节“,这是无用的。
我在这个问题上发现的事情和做过的事情:
相同的值。
我很沮丧,我不知道我错过了什么。以下是我的方法:
- (NSString *)stringFromFileSize:(int)theSize
{
CGFloat floatSize = theSize;
if (theSize<1023)
return([NSString stringWithFormat:@"%i bytes",theSize]);
floatSize = floatSize / 1024;
if (floatSize<1023)
return([NSString stringWithFormat:@"%1.1f KB",floatSize]);
floatSize = floatSize / 1024;
if (floatSize<1023)
return([NSString stringWithFormat:@"%1.2f MB",floatSize]);
floatSize = floatSize / 1024;
return([NSString stringWithFormat:@"%1.2f GB",floatSize]);
}
- (NSUInteger)sizeOfFile:(NSString *)path
{
NSDictionary *fattrib = [[NSFileManager defaultManager] attributesOfItemAtPath:path error:nil];
NSUInteger fileSize = (NSUInteger)[fattrib fileSize];
return fileSize;
}
- (NSUInteger)sizeOfFolder:(NSString*)folderPath
{
NSArray *contents;
NSEnumerator *enumerator;
NSString *path;
contents = [[NSFileManager defaultManager] subpathsAtPath:folderPath];
enumerator = [contents objectEnumerator];
NSUInteger fileSizeInt = 0;
while (path = [enumerator nextObject]) {
NSDictionary *fattrib = [[NSFileManager defaultManager] attributesOfItemAtPath:[folderPath stringByAppendingPathComponent:path] error:nil];
fileSizeInt +=[fattrib fileSize];
}
return fileSizeInt;
}我遗漏了什么?NSFileManager是否返回32位值?是什么引起的?
谢谢!
发布于 2010-10-18 16:08:25
唉,几乎所有的系统都有32位的int,即使您“编译为64位”。(Windows、Mac和Linux都是这样工作的)。见http://en.wikipedia.org/wiki/64-bit#Specific_C-language_data_models。
可以将long传递给stringFromFileSize方法,也可以传递NSUInteger。
发布于 2013-09-20 06:40:57
稍微晚了一点,但是您可以使用这一行并使用正确的数字格式化程序:
NSString *fileSizeStr = [NSByteCountFormatter stringFromByteCount:fileSize countStyle:NSByteCountFormatterCountStyleFile]; https://stackoverflow.com/questions/3960844
复制相似问题