objective c - How to overwrite existing text file, then append to it -
i read settings hardware device , need write them text file, 1 one, 1 line. if file exists, savepanel asks if want overwrite it. answer yes, file gets appended to.
- (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; }
the amended code per answer below
- (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]; } }
the nssavepanel
ui asking user if file should overwritten, other nsopenpanel
/nssavepanel
situations returns selected url(s) application.
your code needs check if file exists , truncate if so, checking if file not exist , creating if so.
you can use methods such truncatefileatoffset:
, functions such ftruncate(2)
, etc.
hth
Comments
Post a Comment