如何使用 C 打开 iOS 中的文件?
How to open a file in iOS using C?
解决方案
没有错误,我没注意。感谢 Rob 指出这一点
我有一个 iOS 应用需要使用 C 库读取文件。
当我尝试从 C 函数访问文件时,我只得到 permission denied error (13) no such file or directory,我找不到原因。当我使用 Swift.
创建、读取或写入时,它不会发生
我尝试了几种在用户数据容器中创建文件 URL 的方法,对 C 不起作用,它只对 Swift 起作用。
即使文件是用Swift创建的,在C调用前后打开、读取和验证,它也只在C中有错误。
我尝试过的事情
// I tried different paths before and added the filename to these directories
// FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first!
// FileManager.default.urls(for: .libraryDirectory, in: .userDomainMask).first!
let path: String = NSTemporaryDirectory().appending("test_file.txt")
FileManager.default.fileExists(atPath: path.path)
// true
XCTAssertNoThrow(try "test".write(to: URL(fileURLWithPath: path), atomically: true, encoding: .utf8))
XCTAssertNoThrow(try FileManager.default.setAttributes([FileAttributeKey.posixPermissions: 0o777], ofItemAtPath: path))
// call C
test_read_file(path)
FileManager.default.fileExists(atPath: path.path)
// true
// test_read_file.c
int test_read_file(const char* path) {
access(file_path, W_OK);
// returns 0
open(path, O_RDONLY);
// returns 13
// errno is 2 (ENOENT: No such file or directory)
return 0;
}
更正
errno
值为 2
ENOENT 2 No such file or directory
13 return 值是一个文件句柄,而不是错误代码,表明您的代码完全按照您的预期工作。
open
returns 非负值表示成功,-1 表示失败。要检查特定错误,请检查 errno
.
解决方案
没有错误,我没注意。感谢 Rob 指出这一点
我有一个 iOS 应用需要使用 C 库读取文件。
当我尝试从 C 函数访问文件时,我只得到 permission denied error (13) no such file or directory,我找不到原因。当我使用 Swift.
我尝试了几种在用户数据容器中创建文件 URL 的方法,对 C 不起作用,它只对 Swift 起作用。
即使文件是用Swift创建的,在C调用前后打开、读取和验证,它也只在C中有错误。
我尝试过的事情
// I tried different paths before and added the filename to these directories
// FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first!
// FileManager.default.urls(for: .libraryDirectory, in: .userDomainMask).first!
let path: String = NSTemporaryDirectory().appending("test_file.txt")
FileManager.default.fileExists(atPath: path.path)
// true
XCTAssertNoThrow(try "test".write(to: URL(fileURLWithPath: path), atomically: true, encoding: .utf8))
XCTAssertNoThrow(try FileManager.default.setAttributes([FileAttributeKey.posixPermissions: 0o777], ofItemAtPath: path))
// call C
test_read_file(path)
FileManager.default.fileExists(atPath: path.path)
// true
// test_read_file.c
int test_read_file(const char* path) {
access(file_path, W_OK);
// returns 0
open(path, O_RDONLY);
// returns 13
// errno is 2 (ENOENT: No such file or directory)
return 0;
}
更正
errno
值为 2
ENOENT 2 No such file or directory
13 return 值是一个文件句柄,而不是错误代码,表明您的代码完全按照您的预期工作。
open
returns 非负值表示成功,-1 表示失败。要检查特定错误,请检查 errno
.