I want to modify (Add a new row) existing csv file in xcode. i have created a csv file programmatically , but when i try to modify it , it delete all the previos data.
i am opening an existing csv file and want to add a next row.
NSString *docFile = [DOCS_FOLDER stringByAppendingPathComponent:#"Questions_Logs.csv"];
NSFileManager* filemanager = [NSFileManager defaultManager];
//---get the contents of file and if content avalbl than append new data and save it--
if ([filemanager fileExistsAtPath:docFile])
{
NSArray *arrCSV = [NSArray arrayWithObjects:strName,strAge,strDesig, nil];
[[arrCSV componentsJoinedByString:#","] writeToFile:docFile atomically:YES encoding:NSUTF8StringEncoding error:NULL];
}
else
{
NSArray *arrCSV = [NSArray arrayWithObjects:#"Name",#"Age",#"Designation", nil];
[[arrCSV componentsJoinedByString:#","] writeToFile:docFile atomically:YES encoding:NSUTF8StringEncoding error:NULL];
}
Read the docs: https://developer.apple.com/library/mac/#documentation/Cocoa/Reference/Foundation/Classes/NSString_Class/Reference/NSString.html#jumpTo_134
"This method overwrites any existing file at path."
See writeToFile in OSX, appending to the file? for the solution.
Related
I am using objective-zip for zip/unzip files within folder. my folder contains multiple images, sqlite db file etc. This is the link from where i downloaded
and i got the code also for zip the folder This is the link of that
ziping of folder is done perfectly but i am not able to unzip that. here is my code.
-(void)makeUnZip{
NSString *stringPath1 = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)objectAtIndex:0];
NSString *stringPath=[stringPath1 stringByAppendingPathComponent:[#"test" stringByAppendingFormat:#".zip"]];
ZipFile *unzipFile = [[ZipFile alloc] initWithFileName:stringPath mode:ZipFileModeUnzip];
NSArray *infos = [unzipFile listFileInZipInfos];
for (NSString *file in infos) {
ZipReadStream *readStream = [unzipFile readCurrentFileInZip];
FileInZipInfo *fileInfo = [unzipFile getCurrentFileInZipInfo];
NSString *fileName = [fileInfo name];
NSLog(#"File Name--- %#",fileName);
NSString *unzipFilePath = [stringPath1 stringByAppendingPathComponent:fileName];
NSString *dir = [unzipFilePath stringByDeletingLastPathComponent];
if (![[NSFileManager defaultManager] fileExistsAtPath:dir isDirectory:nil]) {
[[NSFileManager defaultManager] createDirectoryAtPath:dir attributes:nil];
NSLog(#"created directory %#", dir);
}
}
[unzipFile close];
}
This is link from where i got the reference for unzip
NSLog shows only one file name for all the file and my ziped file of document directory is not unziping.
For example my zip folder contains 3 images abc1.png, abc2.png and abc3.png then NSLog shows abc3.png for all 3 and it is not unziping.
When i am unzipping manually by going to simulator folder then it is showing all the images perfectly.
Can any one look in too it and let me know where I am wrong ?
Finally i have done it with SSZipArchive
Not found enough help for objective-zip.
Thanks kirti mali and vijay to comment.
I'm working on an iPhone app and I need to add a new key-value pair to an existing plist file using objective-c. This is what I've tried so far:
NSString *myFile=[[NSBundle mainBundle] pathForResource:#"Favourites" ofType:#"plist"];
dict = [[NSMutableDictionary alloc] initWithContentsOfFile:myFile];
[dict setObject:textContent forKey:keyName];
[dict writeToFile:myFile atomically:YES];
However, when I do this it doesn't write it to the file. I've only seen resources based on either changing the value of a key or adding to another key. Is there another way to accomplish this?
Thank you for your time
You cannot make any changes in the bundle. So what you have to do is copy the .plist file into your documents directory and do the manipulation there.
Something along these lines:
//check for plist
//Get documents directory's location
NSArray*docDir=NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask, YES);
NSString*filePath=[docDir objectAtIndex:0];
NSString*plistPath=[filePath stringByAppendingPathComponent:#"Favourites.plist"];
//Check plist's existance using FileManager
NSError*err=nil;
NSFileManager*fManager=[NSFileManager defaultManager];
if(![fManager fileExistsAtPath:plistPath])
{
//file doesn't exist, copy file from bundle to documents directory
NSString*bundlePath=[[NSBundle mainBundle] pathForResource:#"Favourites" ofType:#"plist"];
[fManager copyItemAtPath:bundlePath toPath:plistPath error:&err];
}
//Get the dictionary from the plist's path
NSMutableDictionary*plistDict=[[NSMutableDictionary alloc] initWithContentsOfFile:plistPath];
//Manipulate the dictionary
[plistDict setObject:textContent forKey:keyName];
//Again save in doc directory.
[plistDict writeToFile:myFile atomically:YES];
I have one created one folder called "MYFOLDER" inside my folder in have one pdf file test.pdf.
I have one button named browse and the textfield. As soon as I click on the browse button I need to navigate through the folders and select the test.pdf file (Like GMAIL Attachment). After selecting particular file I need to set the file path in the text field.
How to do that?
Thanks in advance.
why not codes?
i appreciated NSFileManager.
NSFileManager *manager = [NSFileManager defaultManager];
NSArray *fileList = [manager directoryContentsAtPath:#"/MYFOLDER"];
NSArray *pdfList = [list filteredArrayUsingPredicate:[NSPredicate predicateWithFormat:#"SELF ENDSWITH '.pdf'"]];
NSLog(#"%#", pdfList);
Use enumeratorAtPath:
Returns a directory enumerator object that can be used to perform a
deep enumeration of the directory at the specified path.
(NSDirectoryEnumerator *)enumeratorAtPath:(NSString *)path Parameters
path
The path of the directory to enumerate.
Return Value
An NSDirectoryEnumerator object that enumerates the contents of the
directory at path.
If path is a filename, the method returns an enumerator object that
enumerates no files—the first call to nextObject will return nil.
Maybe this will help you
[[NSBundle mainBundle] pathForResource:#"test" ofType:#"pdf";];
Then you need to list the files and folders in the folder, and keep on browsing.
NSError *error;
NSString *homeDirectory = NSHomeDirectory();
NSArray *dirContents = [[NSFileManager defaultManager] contentsOfDirectoryAtPath:homeDirectory error:&error];
for(int i = 0; i < [dirContents count]; i++){
//Here you can browse dirContents
NSString *fileName = [dirContents objectAtIndex:i];
}
I am developing an application where i am creating some random .txt file which ultimately stored as a txt file format.
Now for reading these file i am using this code
NSString* documentDirectory = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
NSError* error = nil;
myArray = [[[NSFileManager defaultManager] contentsOfDirectoryAtPath:documentDirectory error:&error]retain];
Now i am displaying the file name in a table view using
cell.textLabel.text = [myArray objectAtIndex:row];
So it curretly displaying like file1.txt,file2.txt etc.
But i donot want the file extension while displaying in the table list.
How can i do that?
cell.textLabel.text = [[myArray objectAtIndex:row] stringByDeletingPathExtension];
Use [yourString stringByDeletingPathExtension] method to remove the extensions from your string. Refer NSString class.
I want to write data to a .txt file without replacing its older contents.I have moved the file from the NSMainBundle to the documents directory.I am able to write the the file by using the code
NSData *data=[NSKeyedArchiver archivedDataWithRootObject:recentMainArray];
NSFileHandle *myHandle = [NSFileHandle fileHandleForUpdatingAtPath:filePath];
[myHandle seekToEndOfFile];
[myHandle writeData:data];
[myHandle closeFile];
But when i try to display the contents of the file,i don't have any data in that.File exists in that path also.This is the following code i use to display the contents.
NSFileManager *manager = [NSFileManager defaultManager];
//filePath - > the documents directory file path
if([manager fileExistsAtPath:filePath]) {
NSMutableArray *savedArray = [[NSMutableArray alloc] initWithContentsOfFile:filePath];
NSMutableArray *storedRecentID = [savedArray objectAtIndex:0];
NSMutableArray *storedRecentName = [savedArray objectAtIndex:1];
NSLog(#"ID:%#",[savedArray objectAtIndex:0]);
NSLog(#"Name:%#",[savedArray objectAtIndex:1]);
}
else {
NSLog(#"file not found, save something to create the file");
}
"null" which is printed as result for those two nslogs.
Please anybody let me know a solution for this problem.FYI,i am using a simulator to test,is this creating a problem.Please suggest me a solution.I have searched a lot and i am not able to find a solution.
Thank you all in advance
Read the data into some Mutable structure (dictionary, array, string) and then append your new data into the same satring. Now write the data into the same path. So the new appended data will be written in file.