从Objective C中的文件中读取字节数组

问题描述 投票:1回答:1

我尝试用字节数据读取文件。

我的文件阅读代码是

    NSString *filepath=[[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:@"PATH.dat"];    
    NSLog(@"\n\nthe string %@",filepath);
    NSData *fileData = [NSData dataWithContentsOfFile: filepath];
    char *fileBytes = (char *)[fileData bytes];
    NSUInteger length = [fileData length];
    NSLog(@"length %lu", (unsigned long)length);
    NSUInteger index;
    for (index = 0; index<length; index++)
    {
        char aByte = fileBytes[index];
        NSLog(@"byte %d", aByte);
    }

以下输出显示文件路径正常,但长度为0。

the string /var/containers/Bundle/Application/6D84F701-BC0E-43AD-8FD8-1F0083CE1F84/ProductName.app/PATH.dat
2017-12-22 17:54:18.746773+0800 ProductName[8704:2173252] length 0

我的文件阅读有什么问题?

编辑:

if([[NSFileManager defaultManager] fileExistsAtPath: filepath])
        NSLog(@"fileexist");
ios objective-c
1个回答
1
投票

尝试使用此方法获取文件的路径:

NSString *filepath = [[NSBundle mainBundle] pathForResource:@"FILENAME" ofType:@"dat"];

如果仍然无效,请尝试:

NSURL *fileUrl = [NSURL fileURLWithPath:filepath];
NSData *fileData = [NSData dataWithContentsOfURL:fileUrl];
© www.soinside.com 2019 - 2024. All rights reserved.