A Collection of Code Snippets in as Many Programming Languages as Possible
This project is maintained by TheRenegadeCoder
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.
#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.
No 'How to Implement the Solution' section available. Please consider contributing.
No 'How to Run the Solution' section available. Please consider contributing.