Searching Through a TextFile - Cocoa
How would I type up a code that searches through a text file from a given directory. I 开发者_运维问答want the search word to be "password123" and if it contains that, then it will proceed onto the next step, if not it will give an error message.
Try this function;
ETA
Okay, I'm an idiot and I typed in code without trying it out first.
This works. I've also got a simple Xcode project which works with this which you can download to try for yourself if I've typed anything wrong in here.
// Get the URL for the Password.txt file on the desktop.
NSURL *fileURL = [NSURL fileURLWithPath:[@"~/Desktop/Password.txt" stringByExpandingTildeInPath]];
// Read the contents of the file into a string.
NSError *error = nil;
NSString *fileContentsString = [NSString stringWithContentsOfURL:fileURL
encoding:NSUTF8StringEncoding
error:&error];
// Make sure that the file has been read, log an error if it hasn't.
if (!fileContentsString) {
NSLog(@"Error reading file");
}
// Create the string to search for
NSString *password = @"Password123";
// Search the file contents for the given string, put the results into an NSRange structure
NSRange result = [fileContentsString rangeOfString:password];
// -rangeOfString returns the location of the string NSRange.location or NSNotFound.
if (result.location == NSNotFound) {
// Password not found. Bail.
NSLog(@"Password not found in file");
return;
}
// Continue processing
NSLog(@"Password found in file");
}
To read a text file:
NSString *path = ...;
NSError *error;
NSString *stringFromFileAtPath = [[NSString alloc]
initWithContentsOfFile:path
encoding:NSUTF8StringEncoding
error:&error];
if (stringFromFileAtPath == nil) {
// an error occurred
NSLog(@"Error reading file at %@\n%@",
path, [error localizedFailureReason]);
// implementation continues ...
Taken from the Apple docs found here.
You could use
NSString rangeOfString:
to search for your string.
More about that here:
Apple Documentation: Searching Strings
If you want to stick to Cocoa, then NSScanner
is your friend.
If you don't bother using plain unix api, you can use:
int match = system("grep -q password123 pathToMyfile");
and check whether match
is 0, in which case a match has been found.
精彩评论