in my iPhone application I need to append binary data to file:
NSError *error;
NSFileManager *fileMgr = [NSFileManager defaultManager];
NSData* data = [NSData dataWithBytes:buffer length:readBytes_];
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *appFile = [documentsDirectory stringByAppendingPathComponent:#"myFile"];
NSFileHandle *myHandle = [NSFileHandle fileHandleForUpdatingAtPath:appFile];
[myHandle seekToEndOfFile];
[myHandle writeData: data];
[myHandle closeFile];
// [data writeToFile:appFile atomically:YES];
// Show contents of Documents directory
NSLog(#"Documents directory: %#",
[fileMgr contentsOfDirectoryAtPath:documentsDirectory error:&error]);
But in NSlog i don't see that there is my file. What is wrong?
If the files does not exist then [NSFileHandle fileHandleForUpdatingAtPath:] will return nil (see the docs).
Therefore check that before attempting to open the file and create it if necessary:
NSFileManager *fileMan = [NSFileManager defaultManager];
if (![fileMan fileExistsAtPath:appFile])
{
[fileMan createFileAtPath:appFile contents:nil attributes:nil];
}
NSFileHandle *myHandle = [NSFileHandle fileHandleForUpdatingAtPath:appFile];
// etc.
And add more error-checking all round.
Related
I'm newbie in iOS. I have a problem.
I log the path of file and I also verify it in Finder. But fileExistsAtPath: return NO, that's why I cannot delete it.
I need help please!!
Here is the code:
+ (void)removeImage:(NSString*)imgName {
MyLog(#"%#", [Tool getFileFullPath:imgName]);
NSFileManager *fileManager = [NSFileManager defaultManager];
NSError *error;
BOOL fileExists = [fileManager fileExistsAtPath:(NSString *)[Tool getFileFullPath:imgName]];
NSLog(#"Path to file: %#", [Tool getFileFullPath:imgName]);
NSLog(#"File exists: %d", fileExists);
NSLog(#"Is deletable file at path: %d", [fileManager isDeletableFileAtPath:[Tool getFileFullPath:imgName]]);
if (fileExists)
{
BOOL success = [fileManager removeItemAtPath:[Tool getFileFullPath:imgName] error:&error];
if (!success) NSLog(#"Error: %#", [error localizedDescription]);
}
}
Path to file: /Users/vibolteav/Library/Application Support/iPhone Simulator/5.1/Applications/FD57CA70-14E4-442D-9CA5-DE7A7AD56A93/Documents/img/2053871632
File exists: 0
Is deletable file at path: 1
for remove file from document directory you use below code:
-(void)removeOneImage:(NSString*)fileName
{
NSFileManager *fileManager = [NSFileManager defaultManager];
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *fullPath = [documentsDirectory stringByAppendingPathComponent:fileName];
NSLog(#"%#",fullPath);
[fileManager removeItemAtPath: fullPath error:NULL];
}
Document Path..
NSArray *searchPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
documentPath_ = [searchPaths objectAtIndex: 0];
Append File name...
NSString *fullPath = [documentsDirectory stringByAppendingPathComponent:fileName];
NSFileManager *fileManager = [NSFileManager defaultManager];
if ([fileManager fileExistsAtPath:fullPath])
{
NSError *error;
if (![fileManager removeItemAtPath:fullPath error:&error]) {
}
}
I am using the following line of code to save my file of yoyo.txt in the Documents folder ::
NSString *docDir = [NSHomeDirectory() stringByAppendingPathComponent:#"Documents"];
NSLog(#"docDir is yoyo :: %#", docDir);
NSString *FilePath = [docDir stringByAppendingPathComponent:#"yoyo.txt"];
However, I wish to save my file in a folder of yoyo i.e. inside the Documents folder i.e. I want to create another folder named as "yoyo" and then save my file of yoyo.txt into it. How can I do that ?? Thanks.
Here is a sample code (assume manager is [NSFileManager defaultManager]):
BOOL isDirectory;
NSString *yoyoDir = [docDir stringByAppendingPathComponent:#"yoyo"];
if (![manager fileExistsAtPath:yoyoDir isDirectory:&isDirectory] || !isDirectory) {
NSError *error = nil;
NSDictionary *attr = [NSDictionary dictionaryWithObject:NSFileProtectionComplete
forKey:NSFileProtectionKey];
[manager createDirectoryAtPath:yoyoDir
withIntermediateDirectories:YES
attributes:attr
error:&error];
if (error)
NSLog(#"Error creating directory path: %#", [error localizedDescription]);
}
+(void)createDirForImage :(NSString *)dirName
{
NSString *path;
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
path = [[paths objectAtIndex:0] stringByAppendingPathComponent:dirName];
NSError *error;
if (![[NSFileManager defaultManager] fileExistsAtPath:path]) //Does directory already exist?
{
if (![[NSFileManager defaultManager] createDirectoryAtPath:path
withIntermediateDirectories:NO
attributes:nil
error:&error])
{
NSLog(#"Create directory error: %#", error);
}
}
}
Here dataPath will be the final path for saving your file
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0]; // Get documents folder
NSString *dataPath = [documentsDirectory stringByAppendingPathComponent:#"/yoyo"];
if (![[NSFileManager defaultManager] fileExistsAtPath:dataPath]){
[[NSFileManager defaultManager] createDirectoryAtPath:dataPath withIntermediateDirectories:NO attributes:nil error:&error]; //Create folder
}
dataPath = [dataPath stringByAppendingPathComponent:#"/yoyo.txt"];
Can any one help me for:
How can we create copy of database?
How can we open that database in iPhone?
How can we create folder in our application path?
How can we copy folder with files in our application path?
"For Creating the copy of Database..."
BOOL success;
NSFileManager *fileManager = [NSFileManager defaultManager];
NSError *error;
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentPath = [paths objectAtIndex:0];
NSString *finalPath = [documentPath stringByAppendingPathComponent:#"test.sqlite"];
success = [fileManager fileExistsAtPath:finalPath];
if(success)
{
NSLog(#"Database Already Created.");
return;
}
NSString *defaultPath = [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:#"test.sqlite"];
success = [fileManager copyItemAtPath:defaultPath toPath:finalPath error:&error];
if(success)
{
NSLog(#"Database Created Successfully.");
}
"For Open that Database..."
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentPath = [paths objectAtIndex:0];
NSString *finalPath = [documentPath stringByAppendingPathComponent:#"test.sqlite"];
if(sqlite3_open([finalPath UTF8String], &database) != SQLITE_OK)
{
sqlite3_close(database);
NSLog(#"Error to Open Database :- %s",sqlite3_errmsg(database));
}
"For Creating Folder in Application Path"
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0]; // Get documents folder
NSString *dataPath = [documentsDirectory stringByAppendingPathComponent:#"/FolderName"];
if (![[NSFileManager defaultManager] fileExistsAtPath:dataPath])
{
[[NSFileManager defaultManager] createDirectoryAtPath:dataPath withIntermediateDirectories:NO attributes:nil error:&error];
}
"For Copying The Files And Folder in Application"
NSFileManager *fileManager = [NSFileManager defaultManager];
NSError *error;
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0]; // Get documents folder
NSString *dataPath = [documentsDirectory stringByAppendingPathComponent:#"/FolderName"];
if (![[NSFileManager defaultManager] fileExistsAtPath:dataPath])
{
BOOL successs;
NSString *defaultPath = [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:#"Files/FolderName"];
successs = [[NSFileManager defaultManager] fileExistsAtPath:defaultPath];
if(successs)
{
NSLog(#"TRUE");
NSString *strFile = [NSString stringWithFormat:#"%#",dataPath];
NSLog(#"File :- '%#'",strFile);
[fileManager copyItemAtPath:defaultPath toPath:strFile error:&error];
}
else
NSLog(#"FALSE");
}
i must write (at start of app) and delete is content (at the end of app) a csv in my sandbox file with a stream of data.
For your experience, what's the best way to do this?
edit:
i'm trying with this:
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *filename =#"test.csv";
NSString *fullPathToFile = [documentsDirectory stringByAppendingPathComponent:filename];
if(![[NSFileManager defaultManager] fileExistsAtPath: fullPathToFile]) {
[[NSFileManager defaultManager] createFileAtPath: fullPathToFile contents:nil attributes:nil];
}
NSFileHandle *handle = [NSFileHandle fileHandleForWritingAtPath: fullPathToFile];
NSString *data = [NSString stringWithFormat:#"%#,%#\n", latitudine.text, longitudine.text];
[handle writeData:[data dataUsingEncoding:NSUTF8StringEncoding]];
it work but.... every time writedata is call i got only one row, no append. i want to collect all values of my two textlabel.
Where my mistake?
edit2:
yessss, find the solution with this code:
first i've create this one:
- (NSString *)dataFilePath {
NSArray *paths = NSSearchPathForDirectoriesInDomains(
NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
return [documentsDirectory stringByAppendingPathComponent:#"myfile.csv"];
}
and in my viewDidLoad i check and if does not exist, create my file
if (![[NSFileManager defaultManager] fileExistsAtPath:[self dataFilePath]]) {
[[NSFileManager defaultManager] createFileAtPath: [self dataFilePath] contents:nil attributes:nil];
NSLog(#"Route creato");
}
and in one of my method i add the code for retrieve data and append to my file:
NSString *data = [NSString stringWithFormat:#"%#,%# ", latitudine.text, longitudine.text];
//create my data to append
NSFileHandle *handle;
handle = [NSFileHandle fileHandleForWritingAtPath: [self dataFilePath] ];
//say to handle where's the file fo write
[handle truncateFileAtOffset:[handle seekToEndOfFile]];
//position handle cursor to the end of file
[handle writeData:[data dataUsingEncoding:NSUTF8StringEncoding]];
//write data to with the right encoding
Hope this helps!
If you put it in NSTemporaryDirectory(), I think it's supposed to be cleaned up on app exit — it's probably worth checking if this is the case.
What am I doing wrong here:
NSArray *paths = NSSearchPathForDirectoriesInDomains (NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
self.gpsFilePath = [documentsDirectory stringByAppendingString: #"/gpsReadings.txt"];
self.gpsFile = [NSFileHandle fileHandleForWritingAtPath:self.gpsFilePath];
[self.gpsFile writeData:#"GPS Readings"];
[self.gpsFile closeFile];
I need to create the file first:
[[NSFileManager defaultManager] createFileAtPath:self.gpsFilePath contents:nil attributes:nil];
Here is the right way to do:
NSString *chemin = #"fichierlocal";
[[NSFileManager defaultManager] createFileAtPath:chemin contents:nil attributes:nil];
NSFileHandle *handle4write = [NSFileHandle fileHandleForWritingAtPath:chemin];
NSString *lemessage = #"Hello, World!";
[handle4write writeData:[lemessage dataUsingEncoding:NSASCIIStringEncoding]];
[handle4write closeFile];