ios fwrite函数EXC_错误访问

ios fwrite函数EXC_错误访问,ios,exc-bad-access,fwrite,Ios,Exc Bad Access,Fwrite,我尝试在iPhone应用程序中使用fwrite(C函数) 出于自定义原因,我不想使用writeToFile而是fwriteC函数 我在didfishlaunchingwithoptions函数中编写了这段代码: FILE *p = NULL; NSString *file= [NSHomeDirectory() stringByAppendingPathComponent:@"Documents/Hello.txt"]; char buffer[80] = "Hello World"

我尝试在iPhone应用程序中使用fwrite(C函数)

出于自定义原因,我不想使用writeToFile而是fwriteC函数

我在didfishlaunchingwithoptions函数中编写了这段代码:

  FILE *p = NULL;
  NSString *file= [NSHomeDirectory() stringByAppendingPathComponent:@"Documents/Hello.txt"];
  char buffer[80] = "Hello World";
  p = fopen([file UTF8string], "w");
  if (p!=NULL) {
      fwrite(buffer, strlen(buffer), 1, p);
      fclose(p);
  }
但是我在fwrite函数中得到了errorEXC_BAD_ACCESS


有什么帮助吗?

你的问题是你写错地方了。使用NSString类中提供的函数要简单得多,它允许您写入文件。进入应用程序沙盒的/Documents文件夹(应用程序沙盒是唯一允许您自由写入文件的地方)

我认为这是最简单的方法。您可以使用fwrite实现同样的功能,只需使用cstringusingencode将路径转换为cstring,如下所示:

NSString *stringToWrite =  @"TESTING";
NSString *path = [NSHomeDirectory() stringByAppendingPathComponent:@"Documents/filename.txt"];
char *pathc =  [path cStringUsingEncoding:NSUTF8StringEncoding];
char *stringToWritec = [stringToWrite cStringUsingEncoding:NSUTF8StringEncoding];

注意:我几乎可以肯定苹果公司使用UTF8编码作为它的文件名。如果没有,请尝试NSASCIIStringEncoding和NSISolatin1StringCodeing。

检查
fopen()
的返回值:打开文件失败时返回
NULL
。我检查了它,它与NULL不同。我用代码编辑我的帖子。这个问题可能很愚蠢,但是。。。为什么不使用标准的
NSFileManager
或使用
-writeToFile:atomicly:encoding:error:
-writeToURL:atomicly:encoding:error:
对象。。。?无法保证您有权使用iPhone上的
fwrite()
函数将文件写入沙箱中……代码是错误的,因为
if
总是错误的。要知道hmjd代码没有错,正如我在给George Aguirre的回答中告诉他的那样,我想使用fwrite在holex的第一篇帖子中更新。但是我一直在这个简单的代码上得到EXC_BAD_访问错误!我现在使用NSHomeDirectory(代码编辑),我看到Hello.txt文件创建但为空,仍然在fwrite函数中执行错误访问。我真的想使用C函数“fwrite”,可能吗?当然,唯一的问题是,fwrite接收的是C字符串,而不是NSstring。因此,在计算路径后,需要将字符串转换为c字符串。我将把代码添加到我的答案中。NSString的UTF8string方法返回C字符串(char*),但我仍然得到ASCII编码的errorTry。要进行调试,可以对cstring使用fprint,对nsstring使用NSLog。
NSString *stringToWrite =  @"TESTING";
NSString *path = [NSHomeDirectory() stringByAppendingPathComponent:@"Documents/filename.txt"];
char *pathc =  [path cStringUsingEncoding:NSUTF8StringEncoding];
char *stringToWritec = [stringToWrite cStringUsingEncoding:NSUTF8StringEncoding];