gpt4 book ai didi

objective-c - 如何覆盖现有文本文件,然后追加到它

转载 作者:行者123 更新时间:2023-12-03 17:38:29 34 4
gpt4 key购买 nike

我从硬件设备读取设置,需要将它们逐一写入到文本文件中,逐行写入。如果文件已存在,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];
}
}

最佳答案

NSSavePanel UI 只是询问用户是否应该覆盖文件,与其他 NSOpenPanel/NSSavePanel 情况一样,它只返回您的应用程序的选定 URL。

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

您可以使用truncateFileAtOffset:等方法、ftruncate(2)等函数等。

HTH

关于objective-c - 如何覆盖现有文本文件,然后追加到它,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30248802/

34 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com