Xcode的应用程序可以为二进制不能打开文件读取
问题描述:
我试图打开一个文件“d.mp3”我加入到我的Xcode 8.0项目。
如果我双击Xcode>项目>'d.mp3'文件播放就好了。
但是,当Xcode在我的iPhone6 +(iOS 10.0.1)上运行我的应用程序时,fopen()为文件句柄返回0。Xcode的应用程序可以为二进制不能打开文件读取
代码和下面输出...
bool read_next_chunk(char* relative_file_pathname, unsigned char* chunk_buffer, int chunk_size_bytes, FILE* file_handle )
{ 常量布尔DBG = TRUE;
// Get absolute file pathname:
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,
NSUserDomainMask, YES);
NSString *program_directory = [paths objectAtIndex:0];
NSString* absolute_pathname = [NSString stringWithFormat: @"%@/%s", program_directory, relative_file_pathname ];
if(dbg) printf("\n%s: file '%s'. Path '%s'.", __FUNCTION__, relative_file_pathname, [absolute_pathname UTF8String]);
// Open file if not already open:
if(file_handle == NULL)
{
if(dbg) printf("\n%s Open file %s.", __FUNCTION__, relative_file_pathname);
file_handle = fopen([absolute_pathname UTF8String], "rb"); // open for binary reading
if(dbg) printf("\n%s file_handle %d.", __FUNCTION__, file_handle);
}
if(file_handle)
{
// Read next chunk of file into file_content_string:
int total_read_bytes = (int)fread(chunk_buffer, 1, chunk_size_bytes, file_handle);
if(total_read_bytes != chunk_size_bytes)
{
printf("\n %s: %d total_read_bytes != %d chunk_size_bytes -- FAULT!! <<<<<<<<<<<",__FUNCTION__, total_read_bytes, chunk_size_bytes);
return false;
}
return true;
}
else
{
printf("\ %s: Cannot open '%s' FAULT!! <<<<<<<<<<<", __FUNCTION__, relative_file_pathname);
return false;
}
}
read_next_chunk:文件 'd.mp3'。路径'/var/mobile/Containers/Data/Application/C8B87C49-C6CF-4677-B775-6B3DF6EFD908/Documents/d.mp3'。
read_next_chunk打开文件d.mp3。
read_next_chunk file_handle 0. read_next_chunk:无法打开'd.mp3'FAULT !! < < < < < < < < < < <
答
正如rmaddy说,它很可能不是在你的文档目录。试试这样的:
NSString* filePath = [[NSBundle mainBundle] pathForResource:@"d" ofType:@"mp3"];
如果文件捆绑在您的应用程序中,它将不会在Documents文件夹中。使用'NSBundle'访问它。 – rmaddy