解决方法如下:
#ifdef __APPLE__
#include "CoreFoundation/CoreFoundation.h"
#endif
// ----------------------------------------------------------------------------
// This makes relative paths work in C++ in Xcode by changing directory to the Resources folder inside the .app bundle
#ifdef __APPLE__
CFBundleRef mainBundle = CFBundleGetMainBundle();
CFURLRef resourcesURL = CFBundleCopyResourcesDirectoryURL(mainBundle);
char path[PATH_MAX];
if (!CFURLGetFileSystemRepresentation(resourcesURL, TRUE, (UInt8 *)path, PATH_MAX))
{
// error!
}
CFRelease(resourcesURL);
chdir(path);
std::cout << "Current Path: " << path << std::endl;
#endif
// ----------------------------------------------------------------------------
具体实现文件如下:
LoadFile.hpp
#ifndef LoadFile_hpp
#define LoadFile_hpp
#ifdef __cplusplus
extern"C" {
#endif
#include <stdio.h>
#ifdef __APPLE__
#include "CoreFoundation/CoreFoundation.h"
#endif
void loadFile();
#ifdef __cplusplus
}
#endif
#endif /* LoadFile_hpp */
LoadFile.cpp
#include "LoadFile.hpp"
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
void loadFile()
{
printf("%s, %d\n", __func__, __LINE__);
ifstream inputFile;
string countries;
// This makes relative paths work in C++ in Xcode by changing directory to the Resources folder inside the .app bundle
#ifdef __APPLE__
CFBundleRef mainBundle = CFBundleGetMainBundle();
CFURLRef resourcesURL = CFBundleCopyResourcesDirectoryURL(mainBundle);
char path[PATH_MAX];
if (!CFURLGetFileSystemRepresentation(resourcesURL, TRUE, (UInt8 *)path, PATH_MAX)) {
// error!
}
CFRelease(resourcesURL);
chdir(path);
std::string sourcePath(path);
#if TARGET_OS_IPHONE || TARGET_OS_TV
// /var/containers/Bundle/Application/8A7E3671-5BE7-4C02-867B-58C53A391397/iOSTest.app/model.bundle/load.bin
std::cout << "Current Path: " << sourcePath << std::endl;
std::cout << "Current Path: " << (sourcePath + "/model.bundle/load.bin") << std::endl;
#elif TARGET_OS_MAC
// /Users/xxxxxx/Library/Developer/Xcode/DerivedData/MacTest-fnhmrwbqmbccbxhjywjehgdoqfib/Build/Products/Debug/MacTest.app/Contents/Resources/model.bundle/load.bin
std::cout << "Current Path: " << sourcePath << std::endl;
std::cout << "Current Path: " << (sourcePath + "/model.bundle/load.bin") << std::endl;
#endif
#endif
inputFile.open(sourcePath + "/load.bin"); // The name of the file you set up.
while(inputFile >> countries) {
cout << countries << endl;
}
inputFile.close();
}
iOS 工程中,.cpp 文件获取资源文件的路径地址为: /var/containers/Bundle/Application/8A7E3671-5BE7-4C02-867B-58C53A391397/iOSTest.app/model.bundle/load.bin
MacOS 工程中,.cpp 文件获取资源文件的路径地址为: /Users/xxxxxx/Library/Developer/Xcode/DerivedData/MacTest-fnhmrwbqmbccbxhjywjehgdoqfib/Build/Products/Debug/MacTest.app/Contents/Resources/model.bundle/load.bin
sourcePath + /model.bundle/load.bin 中,虽然不同平台的 sourcePath 不同,但是都能获取到 load.bin 文件的绝对路径。所以,不用用宏 "TARGET_OS_IPHONE || TARGET_OS_TV", "TARGET_OS_MAC" 来区别是 iOS 还是 Mac 平台了。