简体   繁体   English

如何使用 C 在 iOS 中打开文件?

[英]How to open a file in iOS using C?

Solution解决方案

There was no error, I didn't pay attention.没有错误,我没注意。 Thanks to Rob for pointing this out感谢 Rob 指出这一点


I have an iOS app that need to read files using a C library.我有一个需要使用 C 库读取文件的 iOS 应用程序。

I only get permission denied error (13) no such file or directory when I try to access the file from the C function, and I can't find the cause.当我尝试从 C function 访问文件时,我只收到 权限被拒绝错误 (13) no such file or directory,我找不到原因。 It doesn't happen when I create, read or write using Swift.当我使用 Swift 创建、读取或写入时,它不会发生。

I tried several methods to create file URL inside the user data container, nothing works with C, it only works with Swift.我尝试了几种方法在用户数据容器内创建文件 URL,C 不起作用,它只适用于 Swift。

Even when the file is being created with Swift, being opened, read and verified before and after the C call, it only have errors in C.即使使用 Swift 创建文件,在 C 调用之前和之后打开、读取和验证文件,它也只会在 C 中出现错误。

Things I tried我尝试过的事情

// 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;
}

Correction The errno value is 2 更正 errno值为2

ENOENT 2 No such file or directory

The 13 return value is a file handle, not an error code, and suggests your code is working exactly as you expect. 13 返回值是文件句柄,而不是错误代码,表明您的代码完全按照您的预期工作。

open returns a non-negative value for success, and -1 for failure. open返回一个非负值表示成功,-1 表示失败。 To check the specific error, you check errno .要检查特定错误,请检查errno

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM