Cocoa check for multiple file extensions in folder - cocoa

I need to raise an Alert panel if a folder does not contain files with the extension strings in code below. The "input" textField contains the path string ... Can't get it to work ... Thanks for help.
NSString * filePath = [input stringValue];
NSURL *fileURL = [NSURL fileURLWithPath:filePath];
NSString *theFolder= [fileURL path];
NSFileManager * fileMan = [[NSFileManager alloc] init];
NSArray * files = [fileMan contentsOfDirectoryAtPath:theFolder error:nil];
if (files)
{
for(int index=0;index<files.count;index++)
{
NSString * file = [files objectAtIndex:index];
if (!([file.pathExtension isEqualToString:#"txt"] || [file.pathExtension isEqualToString:#"rtf"] || [file.pathExtension isEqualToString:#"doc"] || [file.pathExtension isEqualToString:#"rtfd"])) {
///alert code

Replace
NSFileManager * fileMan = [[NSFileManager alloc] init];
with
NSFileManager * fileMan = [[NSFileManager defaultManager];
Make sure that
NSString *theFolder= [fileURL path];
gives you a folder and not a filename!
I would recommend to lowercase all strings in the comparison.
Declare a bool variable outside the for loop like
BOOL otherFiles = NO;
if (files) {
for(int index=0;index<files.count;index++)
{
NSString * file = [files objectAtIndex:index];
if (!([file.pathExtension.lowercaseString isEqualToString:#"txt"] ||
[file.pathExtension.lowercaseString isEqualToString:#"rtf"] ||
[file.pathExtension.lowercaseString isEqualToString:#"doc"] ||
[file.pathExtension.lowercaseString isEqualToString:#"rtfd"])
) otherFiles = YES;
}
if (otherFiles) NSRunAlertPanel.....
Make sure that files contains what you expect!

Related

Create PLIST with document path of each file in selected folder

I have a folder called 'thepdfpowerpoints'. I simply want to at launch, create a PLIST file that will create an entry for each PDF in the folder showing the path to that particular file. I have the following set up, and it puts the right number of entries, but each entry is the same path listed 399 times.
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *path = [documentsDirectory stringByAppendingPathComponent:#"mastersonglist.plist"];
NSFileManager *fileManager = [NSFileManager defaultManager];
if (![fileManager fileExistsAtPath: path]) {
path = [documentsDirectory stringByAppendingPathComponent: [NSString stringWithFormat:#"mastersonglist.plist"] ];
}
NSMutableDictionary *data;
if ([fileManager fileExistsAtPath: path]) {
data = [[NSMutableDictionary alloc] initWithContentsOfFile: path];
}
else {
// If the file doesn’t exist, create an empty dictionary
data = [[NSMutableDictionary alloc] init];
}
NSBundle *bundle = [NSBundle mainBundle];
self.files = [bundle pathsForResourcesOfType:#"pdf" inDirectory:#"thepdfpowerpoints"];
NSMutableArray *names = [NSMutableArray arrayWithCapacity:[self.files count]];
for (NSString *pathoffile in self.files) {
pathoffile = [self.files objectAtIndex:thepath.row];
[names addObject:pathoffile];
}
for (NSString *test in names) {
test = [self.files objectAtIndex:thepath.row];
[data setObject:names forKey:#"thename"];
[data writeToFile:path atomically:YES];
}

Using NSArray to display number of .txt files in folder

I need some help with displaying the number of .txt files in a folder.
I can look in a folder for the .txt files:
NSURL *fileURL = [NSURL fileURLWithPath:filePath];
NSString *theFolder= [fileURL path];
NSError *error;
NSString *file;
NSEnumerator *files = [[[NSFileManager defaultManager]
contentsOfDirectoryAtPath:theFolder error:&error] objectEnumerator];
while(file = [files nextObject] ) {
if( [[file pathExtension] isEqualToString:#"txt"] ) {
... and I can display the total number of files in the folder:
NSArray *filelist= [[NSFileManager defaultManager]
contentsOfDirectoryAtPath:myString error:nil];
NSInteger count = [filelist count];
[totalFiles setIntegerValue:count];
I'm stumped on how to only display the number of .txt files in the given folder.
Thanks for the help.
You could do something like this:
NSEnumerator *files = [[[NSFileManager defaultManager]
contentsOfDirectoryAtPath:theFolder error:&error] objectEnumerator];
NSMutableArray *arrayOfTxtFiles = [[NSMutableArray alloc] init];
while(file = [files nextObject] ) {
if( [[file pathExtension] isEqualToString:#"txt"] ) {
[arrayOfTxtFiles addObject: file];
}
}
NSLog( #"count of .txt files is %d", [arrayOfTxtFiles count] );
arrayOfTxtFiles contains all the .txt filenames.
I'm basing my code off your first code snippet, although there may be an even more elegant way to do what you're trying to do.

Problems adding data to a plist file

I've been trying to write data back to a pre-defined plist file (data.plist) in my bundle. Using the code below I call the routine 'dictionaryFromPlist' to open the file and then call 'writeDictionaryToPlist' to write to the plist file. However, no data gets added to the plist file.
NSDictionary *dict = [self dictionaryFromPlist];
NSString *key = #"Reports";
NSString *value = #"TestingTesting";
[dict setValue:value forKey:key];
[self writeDictionaryToPlist:dict];
- (NSMutableDictionary*)dictionaryFromPlist {
NSString *filePath = [[NSBundle mainBundle] pathForResource:#"data" ofType:#"plist"];
NSMutableDictionary* propertyListValues = [[NSMutableDictionary alloc]
initWithContentsOfFile:filePath];
return [propertyListValues autorelease];
}
- (BOOL)writeDictionaryToPlist:(NSDictionary*)plistDict{
NSString *filePath = #"data.plist";
BOOL result = [plistDict writeToFile:filePath atomically:YES];
return result;
}
The code runs through successfully and no error is thrown but no data is added to my plist file.
You can not write to your bundle, it is read only. If your case though, you are writing to a relative path, not to the bundle.
I'm not sure what the default working directory is for iOS apps. It is best to use absolute paths. You should be writing to the documents/cache directory. Something like this will get the path for you:
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
Then just grab the lastObject and prepend that to your file name.
As mentioned by #logancautrell you can not write in mainbundle, you can save your plist in the app documents folder, you could do so:
NSString *path = #"example.plist";
NSArray *paths = NSSearchPathForDirectoriesInDomains (NSDocumentDirectory, NSUserDomainMask, YES);
NSString *basePath = ([paths count]> 0)? [paths objectAtIndex: 0]: nil;
NSString *documentPath = [basePath stringByAppendingPathComponent:path] // Documents
NSFileManager *fileManager = [NSFileManager defaultManager];
BOOL checkfile = [fileManager fileExistsAtPath: documentPath];
NSLog(#"%#", (checkFile ? #"Exist": #"Not exist"));//check if exist
if(!checkfile) {//if not exist
BOOL copyFileToDoc = [yourDictionary writeToFile:documentPath atomically: YES];
NSLog(#"%#",(copyFileToDoc ? #"Copied": #"Not copied"));
}

creating copy of file using file manager is not working for mac app

I have a file in one of the folder in my documents folder .I want to create a copy of that file in some other folder with some other name.The code I am using is
NSFileManager *fileManager = [[NSFileManager alloc] init];
NSString * filePath = [NSHomeDirectory() stringByAppendingPathComponent:
[NSString stringWithFormat:#"Documents/test/test1/%#%#%#",str,currentaudioTobPlayed,#".mp3"]];
NSString * filePath2 = [NSHomeDirectory() stringByAppendingPathComponent:
[NSString stringWithFormat:#"Documents/test/test1/"]];
NSLog(#"filePat %#",filePath);
NSLog(#"filePath2 %#",filePath2);
NSLog(#"filePath2 %#",fileManager);
[fileManager copyItemAtPath:filePath toPath:filePath2 error:NULL];
[fileManager release];
But this code is not working.Please help!
In:
NSString * filePath2 = [NSHomeDirectory() stringByAppendingPathComponent:
[NSString stringWithFormat:#"Documents/test/test1/"]];
you’re not specifying the destination file name: ~/Documents/test/test1 is a directory.
You could do this instead:
NSString *sourceName = [NSString stringWithFormat:#"%#%#.mp3",
str, currentaudioTobPlayed];
// Choose the destination file name
NSString *destName = [NSString stringWithFormat:#"Copy of %#", sourceName];
NSString * filePath = [NSHomeDirectory() stringByAppendingPathComponent:
[NSString stringWithFormat:#"Documents/test/test1/%#", sourceName]];
NSString * filePath2 = [NSHomeDirectory() stringByAppendingPathComponent:
[NSString stringWithFormat:#"Documents/test/test1/%#", destName]];
// Replace Documents/test/test1 with another directory under home,
// or replace the whole string with an entirely different directory

Copy contents of Directories but excluding subdirectories in Cocoa

In Cocoa, is there any way to copy all the files in a directory without copying the directory's subdirectories along with them?
One way would be to copy items in the directory conditionally based on the results of NSFileManagers -fileExistsAtPath:isDirectory::
NSFileManager *manager = [NSFileManager defaultManager];
NSArray *files = [manager contentsOfDirectoryAtPath:pathFrom error:nil];
for (NSString *file in files) {
NSString *fileFrom = [pathFrom stringByAppendingPathComponent:file];
BOOL isDir;
if (![manager fileExistsAtPath:fileFrom isDirectory:&isDir] || isDir) {
continue;
}
NSString *fileTo = [pathTo stringByAppendingPathComponent:file];
NSError *error = nil;
[manager copyItemAtPath:fileFrom toPath:fileTo error:&error];
if (error) // ...
}

Resources