views:

342

answers:

3

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.

+3  A: 

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

weichsel
ok I have the part on searching through a string, but how would I get it so it can search a textfile/?
Kevin
I added the part about reading a text-file to my answer.
weichsel
Ok, I've read all of the documents, and I still can't get an understanding of how to use this. Can someone give me an example that I can follow up from? Thanks...
Kevin
@Kevin: weichsel has given you everything you need. This is a very complete answer. If you can't do it with this info and can't even clearly express why not, I suggest you take a step back, work on some basic Cocoa tutorials and get yourself a good book on the subject. Clearly this topic is beyond you right now and no answer will be sufficient to fill in whatever gap in your knowledge prevents you from using the mountains of information people here have offered you.
Chuck
+2  A: 

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.

mouviciel
Oh cool, I'm just a bit confused of the coding, if the check is 0 how would I translate it into codes, if not then, "this will happen". (i'm sorry, im a beginner at Cocoa, and I'm still learning)
Kevin
If you use system() call, you don't need Cocoa, you can use plain C: `if (match == 0) { proceedOntoTheNextStep; }`
mouviciel
Ok i see, but how would I use NSScanner. I'm not sure which method I should use, and how to use it.
Kevin
I suggest you to read Strings Programming Guide, that you can find at http://developer.apple.com/mac/library/documentation/Cocoa/Conceptual/Strings/introStrings.html.
mouviciel
Ok, I've read all of the documents, and I still can't get an understanding of how to use this. Can someone give me an example that I can follow up from? Thanks...
Kevin
+1 for this approach, since it doesn't require reading the file into memory.
Dave DeLong
+1  A: 

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");    
}
Abizern
-rangeOfString always returns an NSRange struct, and the *location* of that range will be NSNotFound when no match found, not the return value itself. Also note that creating a string with +[NSString stringWithString:] does not make sense at all, because @"Password123" already is an NSString object. So it only makes a copy of it.
JoostK
All good points. Corrected. Thanks. I was more worried about breaking it into lots of steps as an explanation.
Abizern
Ok I get tons of errors when debugging this thing... What's the problem, someone can add it to their code, and they'll get like 15 errors....
Kevin
Ok never mind about the errors, since I just got rid of them, but whenever I try the code it doesn't seem to work... IT's suppose to give an alert if it worked or not, but nothing appears. There is also a warning right about where error: is...
Kevin
@Kevin. I've edited this out. I made some errors in typing the code straight in without testing it first. Sorry.
Abizern
THANKS YOU'RE AWESOME!!!
Kevin
I know I may seem like a pain, Abizern, but how would I be able to read files from a website? Same way like this, but you would get the txt file from the website.
Kevin
Sure you can. If you have a URL to the file location, sure. Look at http://dl.getdropbox.com/u/585261/Example%20Source/File%20reading2.zip which shows you how to do it on my blog. Change the location, but also look at the NSURL Class Reference on some things that need to be done to create a proper NSURL
Abizern
Ok cool thanks!
Kevin
This is awesome and all, but I just have one last question. If I were to make a login system, how would I be able to do it? I know you can inherit this in your code, but when I have more and more people joining, I can't constantly go bizerct and try to make more and more copies of my program with all their names inherited in the program. I want a way so that the program can check it somehow from an external source.
Kevin
There's a big difference between reading a text file and creating a login system. For that you'll need a write methods that pass the username and password to some kind of server, write a routine on the server that validates the user/password combination and returns some kind of token that lets the user continue. If you just want to be able to add licensing to you app, then have a look at the answers to this question. http://stackoverflow.com/questions/889861/registration-for-cocoa-shareware
Abizern
Wow, Thanks a lot for the cool articles!
Kevin
hey, I'm using AquaticMac but the coding for it is given incorrectly, with the framework as well. Take a look: http://aquaticmac.com/guide/validate.php You can try it for yourself. :)
Kevin
Sorry, is there a question in there?
Abizern
-_-, ok " Can you help me with the code from Aquaticmac, since I am not sure how to include it to my program?"
Kevin
How far have you got with the instructions in the link?
Abizern
I've gone all the way to Validate.
Kevin
But I'm stuck on that step
Kevin
So you've added the header the framework and the flag?
Abizern
no not yet... I'm having trouble with that too.... Can you make an example code from xcode that I could download from, so I can see what I did wrong. Since I think there are a million of things that are wrong about my code.
Kevin
No. An example app will depend on how you have your system set up to use the external framework. Go watch this screencast - http://cocoacast.com/?q=node/57 , try writing some code for yourself, and then ask specific questions about the problems you have.
Abizern
Ok. Thanks for the link, that's all I really neaded.
Kevin
I get this error when debugging this with the new project I made :http://www.heliotop.org/License%20App.zipI am doing this on 10.6 but its set to 10.5
Kevin
Set the architecture to 32-bit Universal; add the -lcrypto flag. You don't need the library AND the framework. Builds fine for me.
Abizern
how would I add the -lcrypto flag?
Kevin
NVM, AWESOME IT WORKS!!! Dang i said awesome 3 times on this long comment board. LOL
Kevin
Man! I always end up back with a problem. Ok do you think this can run on my 10.6 app? My 10.6 application has NSRunningApplication Involved in it, which I really need in it.
Kevin
I don't know. What have you tried?
Abizern
Ok yea, I tried doing it, but I get this error from the GDB:_TERMINATING_DUE_TO_UNCAUGHT_EXCEPTION___right after it says, "linking" this happens.
Kevin
This is with all the same settings as the License App i showed you.
Kevin
Dangit, what am I saying. I mean i set the the build to be 10.6, and it to be DEBUG, with the architecture to be 32bit. It gives me the error previously said.
Kevin
Add this to your Global breakpoints: `objc_exception_throw` and see what the stack shows you has gone wrong. All this is basic debugging.
Abizern
I don't think anything is going wrong, it just stops at break point 1
Kevin
Also can Aquatic Prime run on 10.6 Snow leopard? Has anyone tried?
Kevin
Hey @Kevin, Any updates on this question? http://stackoverflow.com/questions/1555936/using-vb-net-to-log-into-windows-live-mail
George Stocker
@Abizern I've decided to make a new thread since this comment bar was getting to long: http://stackoverflow.com/questions/1561838/aquatic-prime-on-10-6
Kevin