Log File to NSString - macos

I am using this to get the log files data:
NSFileHandle *file;
file = [NSFileHandle fileHandleForReadingAtPath:#"~/Library/Application Support/RepoManager/*.log"];
NSData *filedata;
filedata = [file readDataToEndOfFile];
NSString *logC;
logC = [[NSString alloc] initWithData:filedata encoding:NSASCIIStringEncoding];
And than write them using this:
NSString *formatString = #"Log: %#";
return [NSString stringWithFormat:formatString, *logC.stringValue];
But it says logC does not contain a string value

NSString does not define a .stringValue property, and even if it did, *logC.stringValue would have no useful meaning in Objective-C. logC itself is what you want to be using as your format parameter. (It's the string containing the contents of the log file.)

Related

What’s the correct way to create an NSURL from an NSString?

I’ve got an NSString that stores the path to a saved file:
NSString *filePath = [NSString stringWithFormat:
#"%#/someFolder/%#",
NSHomeDirectory(),
[NSString stringWithFormat:#"%#",[self.fileName stringByAppendingPathExtension:#"txt"]]];
And it’s OK — when I log it, I get:
/Users/username/someFolder/fileName.txt
So my next step is to make an NSURL object from this NSString. I did this:
NSURL *pathURL = [NSURL URLWithString:[NSString stringWithFormat:#"%#", filePath]];
NSLog(#"URL = %#", pathURL);
but the response is:
URL = (null)
What’s wrong here? How can I do this correctly?
A path is not a valid URL by itself. You have to use this:
NSURL *pathURL = [NSURL fileURLWithPath:filePath];
And read the documentation. (And don’t overuse / abuse format strings.)

How to Search for the unix executable file in OS X programmatically?

So, I need to search for the Unix Executable files in a directory. I Iterate through directory and with the path of the file I am searching. Some of the Methods I tried.
1.With the Help of the file Extension
Unix Executable file does not have the file Extension, but Some documents files are also not having the extensions. So, it failed for me.
2. With the help of NSFileManager
NSDicitionary *fileAttributes = [[NSFileManager defaultManager] attributesOfItemAtPath:filePath error:nil];
It does not have any unique attributes to find the Unix executable file.
3. With the help of MDItemRef
It have the attribute called kMDItemContentType but it is giving the correct result for some of the unix executable files only.
MDItemRef inspectedRef;
CFArrayRef inspectedRefAttributeNames;
CFDictionaryRef inspectedRefAttributeValues;
inspectedRef = MDItemCreate(kCFAllocatorDefault,(CFStringRef)filePath);
if(inspectedRef) {
inspectedRefAttributeNames = MDItemCopyAttributeNames(inspectedRef);
inspectedRefAttributeValues = MDItemCopyAttributes(inspectedRef,inspectedRefAttributeNames);
NSDictionary *attribDict = (__bridge NSDictionary*)inspectedRefAttributeValues;
if([[attribDict objectForKey:#"kMDItemContentType"] isEqualToString:#"public.unix-executable"])
NSLog(#"Unix Executable file");
}
4. With the help of unix command "file"
NSTask *unixTask = [[NSTask alloc] init];
[unixTask setStandardOutput:newPipe];
[unixTask setLaunchPath:#"/usr/bin/file"];
[unixTask setArguments:[NSArray arrayWithObject:filePath]];
[unixTask launch];
[unixTask waitUntilExit];
[unixTask terminationStatus];
while ((inData = [readHandle availableData]) && [inData length]) {
returnValue= [[NSString alloc] initWithData:inData encoding:[NSString defaultCStringEncoding]];
returnValue = [returnValue substringToIndex:[returnValue length]-1];
NSLog(#"%#",returnValue);
}
Here, From the returnValue I can able to find whether it is unix executable or not. But it is very slow Process. So, My question is How to search for the unix executable in an efficient manner ?
Try using either getResourceValue:forKey:error: or resourceValuesForKeys:error: methods of NSURL and requesting NSURLTypeIdentifierKey.
Addendum:
If what #Aravindhanarvi says is correct, on 10.6 there are bugs and the above solution is unreliable. To make things worse #petur solution is also not possible for lack of NSURLIsExecutableKey.
An alternative would be to fall back to the NSFileManager and use methods like isExecutableFileAtPath: and attributesOfItemAtPath:error: (specifically the NSFilePosixPermissions and NSFileType attributes) to implement the same logic suggested by #petur.
Came up with this, just point the url to the directory you to use as the base.
This is ARC code.
The array, files, contains an url pointer to each executable file found.
#autoreleasepool {
NSFileManager *defaultFileManager = [NSFileManager defaultManager];
NSURL *url = [NSURL URLWithString:#"/private/tmp/"]; // Search path
NSDirectoryEnumerator *dirEnumerator = [defaultFileManager enumeratorAtURL:url includingPropertiesForKeys:[NSArray arrayWithObjects:NSURLNameKey, nil] options:0 errorHandler:nil];
NSMutableArray *files = [NSMutableArray array];
// extract non-executable files
for (NSURL *file in dirEnumerator) {
NSNumber *isExecutable;
NSNumber *isDirectory; // Directories have the executable flag set, but we are not interested in them
NSError *error, *error2;
[file getResourceValue:&isExecutable forKey:NSURLIsExecutableKey error:&error];
[file getResourceValue:&isDirectory forKey:NSURLIsDirectoryKey error:&error2];
// Deal with errors
if (error)
NSLog(#"%#", [error localizedDescription]);
else if (error2)
NSLog(#"%#", [error2 localizedDescription]);
else if ([isExecutable boolValue] && ![isDirectory boolValue]) {
[files addObject:file];
}
// print out all executable files to the console
for (id i in files)
NSLog(#"%#", [i description]);
}

Reading desktop plist

I am using following code to read the details of the plist,
NSString *plistPath = #"~/Library/Preferences/com.apple.desktop.plist";
NSDictionary *plistData = [NSDictionary dictionaryWithContentsOfFile:plistPath];
But plistData has no entries.
Is there something wrong in above code?
You need expanding the tilde. Try this:
NSString * plistPath = [#"~/Library/Preferences/com.apple.desktop.plist" stringByExpandingTildeInPath];

Use stringWithFormat: as a file path in cocoa

I'm having a problem with a cocoa application that takes the value of a text field, and writes it to a file. The file path is made using stringWithFormat: to combine 2 strings. For some reason it will not create the file and the console says nothing. Here is my code:
//Get the values of the text field
NSString *fileName = [fileNameTextField stringValue];
NSString *username = [usernameTextField stringValue];
//Use stringWithFormat: to create the file path
NSString *filePath = [NSString stringWithFormat:#"~/Library/Application Support/Test/%#.txt", fileName];
//Write the username to filePath
[username writeToFile:filePath atomically:YES];
Thanks for any help
The problem is that you have a tilde ~ in the path. ~ is expanded by the shell to the user's home directory, but this doesn't happen automatically in Cocoa. You want to use -[NSString stringByExpandingTildeInPath]. This should work:
NSString *fileName = [fileNameTextField stringValue];
NSString *username = [usernameTextField stringValue];
NSString *fileName = [fileName stringByAppendingPathExtension:#"txt"]; // Append ".txt" to filename
NSString *filePath = [[#"~/Library/Application Support/Test/" stringByExpandingTildeInPath] stringByAppendingPathComponent:fileName]; // Expand '~' to user's home directory, and then append filename
[username writeToFile:filePath atomically:YES];
Adding to mipadi's reply, it's better to use -[NSString stringByStandardizingPath] since it does more - and can clean up more problems - than resolving the tilde.

Declare String then open string from Path with Cocoa

I've Declared a string Like so
NSString* fileName = [files objectAtIndex:i];
NSLog(fileName);
NSImage* imageFromBundle = [[NSImage alloc] initWithContentsOfFile:fileName];
and want to use that filename to open a file in a different directory.
I came up with this
NSImage* imageFromBundle2;
imageFromBundle2 = [[NSImage alloc] initWithContentsOfFile:#"/Users/rhaynes/Documents/works4/" filename ];
Any help would be appreciated
I'll assume that your fileName string is actually a file name, like "myImage.png". A lot of the Objective-C docs refer to a file name when they really mean file path - so sometimes it's confusing.
What you want to do is create an NSString that represents the complete path to the file you want to load. For instance, you could say:
NSString * path = [NSString stringWithFormat: #"/Users/rhaynes/Documents/works4/%#", fileName];
That line creates a new NSString using the format string and parameters provided (the %# in the format string indicates that the string value of fileName should be inserted there.) StringWithFormat is a really powerful function, so you should definitely check it out in the docs.
Then you could call initWithContentsOfFile:path, and it should give you the image you want.
NSString* fileName = [files objectAtIndex:i]; NSLog(fileName);
Don't pass non-hard-coded strings as format-string arguments. If they contain format specifiers, you'll get garbage or a crash. (Try this with fileName = #"foo%sbar", for example. Then try it with fileName = #"foo%fbar" for even more fun.)
Your NSLog statement should be:
NSLog(#"%#", fileName);
[I] want to use that filename to open a file in a different directory. I came up with this
NSImage* imageFromBundle2; imageFromBundle2 = [[NSImage alloc] initWithContentsOfFile:#"/Users/rhaynes/Documents/works4/" filename ];
You can only concatenate string literals this way; as you've no doubt seen for yourself, this is a syntax error when one of the strings isn't a literal.
First off, if fileName is actually a pathname, you'll need to use lastPathComponent to get the actual filename. So:
NSString *path = [files objectAtIndex:i];
NSString *filename = [path lastPathComponent];
Then, use stringByAppendingPathComponent: to tack this onto the new superpath.
NSString *desiredFilenamePath = [directoryPath stringByAppendingPathComponent:filename];
Now you have the pathname you wanted to pass to NSImage's initializer.

Resources