如何覆盖现有的文本文件,然后附加到它

时间:2015-05-14 22:54:12

标签: objective-c macos cocoa

我从硬件设备读取设置,需要将它们逐个写入一个文本文件。如果该文件已存在,则SavePanel会询问是否要覆盖它。我回答是,但文件被附加到。

- (IBAction)saveSettings:(id)sender
 {
   self.saveSettings = TRUE;
   self.firstWrite = TRUE;
   NSSavePanel *saveText    = [NSSavePanel savePanel];
   [saveText setNameFieldStringValue:@"SavedSettings.txt"];
   [saveText setDirectoryURL:[NSURL fileURLWithPath:@"Documents"]];
   [saveText setShowsTagField:NO];
   NSInteger saveInt    = [saveText runModal];
   if(saveInt == NSModalResponseOK)
   {
     NSURL *pathURL = [saveText URL];
     self.pathName = [pathURL path];
     [self appendToFile:@"General configuration\n"];
     [self appendToFile:@"1\n"];
     [self appendToFile:@"1\n"];
     [self appendToFile:@"Configuration axis 1\n"];
     [self readMoveDelayAxis1];
   }
}

- (BOOL)appendToFile:(NSString *)strcontent;
{
  BOOL result = YES;
  NSFileHandle* fh = [NSFileHandle fileHandleForWritingAtPath:self.pathName];
if ( !fh ) 
{
  [[NSFileManager defaultManager] createFileAtPath:self.pathName contents:nil attributes:nil];
  fh = [NSFileHandle fileHandleForWritingAtPath:self.pathName];
}
if ( !fh ) return NO;
@try {
  [fh seekToEndOfFile];
  self.firstWrite = FALSE;
  [fh writeData:[strcontent dataUsingEncoding:NSUTF8StringEncoding]];
}
@catch (NSException * e) {
    result = NO;
}
[fh closeFile];
return result;
}

根据以下答案修改的代码

- (IBAction)saveSettings:(id)sender
{
    self.saveSettings = TRUE;
    NSSavePanel *saveText   = [NSSavePanel savePanel];
    [saveText setNameFieldStringValue:@"SavedSettings.txt"];
    [saveText setDirectoryURL:[NSURL fileURLWithPath:@"Documents"]];
    [saveText setShowsTagField:NO];
    NSInteger saveInt   = [saveText runModal];
    if(saveInt == NSModalResponseOK)
    {
        NSURL *pathURL = [saveText URL];
        NSFileManager *filemgr;
        filemgr = [NSFileManager defaultManager];

        if ([filemgr fileExistsAtPath:[pathURL path]] == YES)
        {
            [filemgr removeItemAtPath:[pathURL path] error: NULL];
        }
        self.pathName = [pathURL path];
        [self appendToFile:@"General configuration\n"];
        [self appendToFile:@"1\n"];
        [self appendToFile:@"1\n"];
        [self appendToFile:@"Configuration axis 1\n"];
        [self readMoveDelayAxis1];
    }
}

1 个答案:

答案 0 :(得分:2)

NSSavePanel用户界面只是询问用户是否应覆盖该文件,与其他NSOpenPanel / NSSavePanel情况一样,它只会将选定的网址返回给您的应用程序。

您的代码需要检查文件是否已经存在,如果是,则截断它,类似于它已经检查文件是否不存在,如果是,则创建它。

您可以使用truncateFileAtOffset:等方法,ftruncate(2)等功能

HTH