1

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.

Jay
  • 19,649
  • 38
  • 121
  • 184
lab12
  • 6,400
  • 21
  • 68
  • 106

3 Answers3

4

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
  • 146,289
  • 39
  • 203
  • 257
  • -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. – Joost Oct 11 '09 at 17:51
  • All good points. Corrected. Thanks. I was more worried about breaking it into lots of steps as an explanation. – Abizern Oct 11 '09 at 17:59
  • 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.... – lab12 Oct 11 '09 at 22:49
  • 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:&error; is... – lab12 Oct 11 '09 at 22:55
  • @Kevin. I've edited this out. I made some errors in typing the code straight in without testing it first. Sorry. – Abizern Oct 12 '09 at 00:03
  • 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. – lab12 Oct 12 '09 at 02:06
  • 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 Oct 12 '09 at 02:27
  • 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. – lab12 Oct 12 '09 at 12:06
  • 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 Oct 12 '09 at 13:39
  • 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. :) – lab12 Oct 12 '09 at 14:54
  • Sorry, is there a question in there? – Abizern Oct 12 '09 at 16:09
  • -_-, ok " Can you help me with the code from Aquaticmac, since I am not sure how to include it to my program?" – lab12 Oct 12 '09 at 17:42
  • How far have you got with the instructions in the link? – Abizern Oct 12 '09 at 18:22
  • I've gone all the way to Validate. – lab12 Oct 12 '09 at 18:42
  • 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. – lab12 Oct 12 '09 at 19:43
  • 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 Oct 12 '09 at 20:00
  • Ok. Thanks for the link, that's all I really neaded. – lab12 Oct 12 '09 at 20:11
  • I get this error when debugging this with the new project I made : http://www.heliotop.org/License%20App.zip I am doing this on 10.6 but its set to 10.5 – lab12 Oct 12 '09 at 22:54
  • 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 Oct 12 '09 at 23:33
  • how would I add the -lcrypto flag? – lab12 Oct 12 '09 at 23:39
  • NVM, AWESOME IT WORKS!!! Dang i said awesome 3 times on this long comment board. LOL – lab12 Oct 12 '09 at 23:42
  • 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. – lab12 Oct 12 '09 at 23:58
  • 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. – lab12 Oct 13 '09 at 01:09
  • This is with all the same settings as the License App i showed you. – lab12 Oct 13 '09 at 01:11
  • 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. – lab12 Oct 13 '09 at 01:15
  • 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 Oct 13 '09 at 04:42
  • I don't think anything is going wrong, it just stops at break point 1 – lab12 Oct 13 '09 at 12:05
  • Also can Aquatic Prime run on 10.6 Snow leopard? Has anyone tried? – lab12 Oct 13 '09 at 12:06
  • Hey @Kevin, Any updates on this question? http://stackoverflow.com/questions/1555936/using-vb-net-to-log-into-windows-live-mail – George Stocker Oct 13 '09 at 15:08
  • @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 – lab12 Oct 13 '09 at 17:48
3

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

Thomas Zoechling
  • 34,177
  • 3
  • 81
  • 112
  • ok I have the part on searching through a string, but how would I get it so it can search a textfile/? – lab12 Oct 08 '09 at 23:20
  • 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... – lab12 Oct 11 '09 at 12:58
  • @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 Oct 12 '09 at 00:09
1

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
  • 66,855
  • 13
  • 106
  • 140
  • 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) – lab12 Oct 09 '09 at 22:04
  • If you use system() call, you don't need Cocoa, you can use plain C: `if (match == 0) { proceedOntoTheNextStep; }` – mouviciel Oct 10 '09 at 11:30
  • Ok i see, but how would I use NSScanner. I'm not sure which method I should use, and how to use it. – lab12 Oct 10 '09 at 17:52
  • 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 Oct 10 '09 at 18:59
  • 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... – lab12 Oct 11 '09 at 12:59
  • +1 for this approach, since it doesn't require reading the file into memory. – Dave DeLong Oct 11 '09 at 17:29