File Input Output in Objective-C

Published on 04 October 2020 (Updated: 30 April 2026)

Welcome to the File Input Output in Objective-C page! Here, you'll find the source code for this program as well as a description of how the program works.

Current Solution

#import <Foundation/Foundation.h>
#include <stdlib.h>

@interface NSString (FileIO)
- (BOOL)writeToDefaultPath:(NSString*)path error:(NSError**)error;
+ (nullable instancetype)stringWithDefaultPath:(NSString*)path
                                         error:(NSError**)error;
@end

@implementation NSString (FileIO)

- (BOOL)writeToDefaultPath:(NSString*)path error:(NSError**)error {
    NSURL* url = [NSURL fileURLWithPath:path];
    return [self writeToURL:url
                 atomically:YES
                   encoding:NSUTF8StringEncoding
                      error:error];
}

+ (instancetype)stringWithDefaultPath:(NSString*)path error:(NSError**)error {
    NSURL* url = [NSURL fileURLWithPath:path];
    return [self stringWithContentsOfURL:url
                                encoding:NSUTF8StringEncoding
                                   error:error];
}

@end

int main(int argc, const char* argv[]) {
    @autoreleasepool {
        NSString* path = @"output.txt";
        NSString* content = @"Hello!\nGoodbye!\n";
        NSError* error = nil;

        if (![content writeToDefaultPath:path error:&error]) {
            fprintf(stderr, "Write Error: %s\n",
                    error.localizedDescription.UTF8String);
            return EXIT_FAILURE;
        }

        NSString* result = [NSString stringWithDefaultPath:path error:&error];
        if (!result) {
            fprintf(stderr, "Read Error: %s\n",
                    error.localizedDescription.UTF8String);
            return EXIT_FAILURE;
        }

        printf("%s", result.UTF8String);
    }
    return EXIT_SUCCESS;
}

File Input Output in Objective-C was written by:

If you see anything you'd like to change or update, please consider contributing.

How to Implement the Solution

No 'How to Implement the Solution' section available. Please consider contributing.

How to Run the Solution

No 'How to Run the Solution' section available. Please consider contributing.