我想读取一个文件(hello.in)并逐行将其写入另一个文件。 我写下面的方法,当我运行它时,我得到sigabrt错误。 我很想得到答案。
-(void) saveAsLineLine: (NSString*) fileName
{
NSString *filePath;
filePath = [NSString stringWithFormat:@"%@%@", pathdir, @"hello.in"];
// reading the file
NSString *entireFileInString = [NSString stringWithContentsOfFile:filePath encoding:(NSUTF8StringEncoding) error:nil];
// each line, adjust character for line endings
NSArray *lines = [entireFileInString componentsSeparatedByString:@"\n"];
filePath = [NSString stringWithFormat:@"%@%@", pathdir, fileName];
// create a file
[[NSFileManager defaultManager] createFileAtPath:filePath contents:nil attributes:nil];
// open the file for writeing
NSFileHandle *fh = [NSFileHandle fileHandleForWritingAtPath:filePath];
// write line by line
for (NSData *line in lines)
{
NSLog (@"line: %@\n", line);
[fh seekToEndOfFile];
[fh writeData: line]; // THE BUG IS HERE !!!!!!!!
// @try {
// [fh writeData: line];
//
// }
// @catch (NSException *exception) {
// NSLog(@"%@",[exception description]);
// }
}
[fh closeFile];
}
答案 0 :(得分:1)
NSArray
lines
包含NSString
,而不是NSData
的实例,对吗?
如果要将数据写入文件......
[lines enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
NSData *lineData = [obj dataUsingEncoding:NSUTF8StringEncoding];
[fh seekToEndOfFile];
[fh writeData:lineData];
}];