Write data to a file without removing the old contents in iPhone - iphone

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.

Related

Not able to unzip folder objective c

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.

How to modify csv file programmatically in Xcode?

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.

creating a binary (.bin) file and read values from file in iphone

Hi i am trying to save text values as binary file and read from that file. i am using following code, i got the binary file in documents directory but when reading data from file only got some numbers please kindly help its urgent.
For writing
NSString *documentsDirectoryPath = [self performSelector:#selector(tempDirectoryPath:) withObject:fileName_];
NSLog(#"%#",documentsDirectoryPath);
if ([[NSFileManager defaultManager] isWritableFileAtPath:documentsDirectoryPath]) {
NSLog(#"content =%#",data_);
[data_ writeToFile:documentsDirectoryPath atomically:YES];
return YES;
}
For reading i use the following code,
NSString *documentsDirectoryPath = [self performSelector:#selector(tempDirectoryPath:) withObject:fileName_];
if ([[NSFileManager defaultManager] isReadableFileAtPath:documentsDirectoryPath]) {
NSMutableData *data_ = [NSMutableData dataWithContentsOfFile:documentsDirectoryPath];
return data_;
}
I got only numbers from the data_ .
How to read the .bin file correctly.?
I got the .bin file when extract get .bin.cpgz file.I can't open the file what is the reason ?Is anything wrong in code?
I am pass string in this way:
[self writeData:#"test string is here" toFile:#"mf.bin"];
Thanks.
It's a little late, but something like this might help you:
http://snippets.aktagon.com/snippets/475-How-to-use-NSKeyedArchiver-to-store-user-settings-on-the-iPhone
Sounds like you need to convert the data into something readable.
NSString *myFile = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
This assumes originally the data you wrote was a NSString, if it was an object you would have to use the appropriate methods for that object.

How to read the files sequentially from a subfolder in document directory of iPhone

I am saving some images in to the documents directory of the app using the following code.
for (int k=0;k<[_imageNames count];k++)
{
NSString *imagePath = [dataPath stringByAppendingPathComponent:[NSString stringWithFormat:#"%d.jpg",k]];
NSData *data = UIImageJPEGRepresentation([_imageNames objectAtIndex:k], 1.0f);
[data writeToFile:imagePath atomically:YES];
}
Now I am trying to load the images sequentially into an NSMutableArray.
Can someone point me towards the right direction.
Try using the name of the file, iterating through and checking if the file exists:
[[NSFileManager defaultManager] fileExistsAtPath:imagePath]
When it returns NO then you know there are no more files to add.

iPhone - file properties

i m creating an application which makes the iphone work as a pendrive for easy file sharing purpose.
In the first stage, i have some files(png, pdf, jpg, zip) in a directory and i made them display in the tableview in the form of mutable array. It displays in the tableView as shown below,
.DS_Store
.localized
gazelle.pdf
Hamburger_sandwich.jpg
IITD TAJ Picture 028_jpg.jpg
iya_logo_final_b&w.jpg
manifesto09-eng.pdf
RSSReader.sql
SimpleURLConnections.zip
SQLTutorial
I just want to display the name of the files and i do not want to display the extensions. I know that it is possible to extract the extensions of a file in NSFileManager. But i do not know how. Please help me to make my table view look like this
.DS_Store
.localized
gazelle
Hamburger_sandwich
IITD TAJ Picture 028_jpg
iya_logo_final_b&w
manifesto09-eng
RSSReader
SimpleURLConnections
SQLTutorial
In the second stage i have a detailedViewController which takes displays the detailed view of the file like
file size
file type
if it is a image, it should open in imageView
if it is a song, it should play it
So i need to retrive the properties like filePath, fileType, fileSize.. of each files. Please guide me with a tutorial if possible. I too do not have any idea how to convert a mutableArray to a NSString and call the methods like stringByDeletingPathExtension. Please help me. I can even send my source code if needed. If possible, guide me with some example codes and tutorial.
This should work:)
This will get all files in a directory in a NSString *parentDirectory, get its size, if image do something otherwise it assumes is a sound file
NSFileManager *fm = [NSFileManager defaultManager];
NSError *error = nil;
NSArray *filePaths = [fm contentsOfDirectoryAtPath:parentDirectory error:&error];
if (error) {
NSLog(#"%#", [error localizedDescription]);
error = nil;
}
for (NSString *filePath in filePaths) {
//filename without extension
NSString *fileWithoutExtension = [[filePath lastPathComponent] stringByDeletingPathExtension];
//file size
unsigned long long s = [[fm attributesOfItemAtPath:[parentDirectory stringByAppendingPathComponent:filePath]
error:NULL] fileSize];
UIImage *image = [UIImage imageNamed:[parentDirectory stringByAppendingPathComponent:filePath];];
//if image...
if(image){
//show it here
}
else{
//otherwise it should be music then, play it using AVFoundation or AudioToolBox
}
}
I hope you will have the file name in NSURL object, if so then you can use the following code to get just the file name and can remove the file extension from the string.
NSArray *fileName = [[fileURL lastPathComponent] componentsSeparatedByString:#"."];
NSLog(#"%#",[fileName objectAtIndex:0]);