首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >FileSize问题-可可

FileSize问题-可可
EN

Stack Overflow用户
提问于 2010-10-18 15:50:17
回答 2查看 219关注 0票数 1

我编写了一些方法,这些方法可以帮助我获得文件/文件夹的大小,并将结果转换为人类可读的字符串。问题是,当这个大小超过2.1GB时,返回的数字会更改为一个随机负数,如"-4324234423字节“,这是无用的。

我在这个问题上发现的事情和做过的事情:

  • 32 as仅限于此大小,因此我使用64位进行编译。
  • 我尝试使用CGFloat和NSUInteger,但它们仍然返回与NSInteger.

相同的值。

我很沮丧,我不知道我错过了什么。以下是我的方法:

代码语言:javascript
复制
- (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位值?是什么引起的?

谢谢!

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 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

票数 2
EN

Stack Overflow用户

发布于 2013-09-20 06:40:57

稍微晚了一点,但是您可以使用这一行并使用正确的数字格式化程序:

代码语言:javascript
复制
NSString *fileSizeStr = [NSByteCountFormatter stringFromByteCount:fileSize countStyle:NSByteCountFormatterCountStyleFile]; 
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/3960844

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档