Search code examples
iosexc-bad-accessfwrite

ios fwrite function EXC_BAD_ACCESS


I try to use fwrite (C function) in iPhone app.

For custom reasons, I don't want to use writeToFile but fwrite C function.

I wrote this code in didFinishLaunchingWithOptions function :

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

But I get error EXC_BAD_ACCESS in fwrite function.

Any help ?


Solution

  • Your problem is you are writing in the wrong place. It is far simpler to use the functions provided in the NSString class, which allow you to write to a file. Get to the /Documents folder of your app's sandbox (your app's sandbox is the only place you are allowed to write files freely)

    NSString *stringToWrite =  @"TESTING";
    NSString *path = [NSHomeDirectory() stringByAppendingPathComponent:@"Documents/filename.txt"];
    [stringToWrite writeToFile:path atomically:YES encoding NSUTF8StringEncoding];
    

    I think this is the simplest approach. You could to the same with fwrite, you would just need to convert the path to a cstring using cstringUsingEncoding, like this:

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

    NOTE: I'm almost sure that apple uses UTF8 encoding for it's file names. If not, try NSASCIIStringEncoding and NSISOLatin1StringEncoding.