[英]Searching Through a TextFile - Cocoa
如何輸入從給定目錄中搜索文本文件的代碼。 我希望搜索詞為“ password123”,如果包含該詞,則它將繼續進行下一步,如果沒有,它將給出錯誤消息。
試試這個功能;
預計到達時間
好的,我是個白痴,沒有先嘗試就輸入了代碼。
這可行。 我還有一個簡單的Xcode項目 ,可以使用該項目進行下載,如果我在此處鍵入任何錯誤,都可以下載以自己嘗試。
// 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");
}
讀取文本文件:
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 ...
摘自此處找到的Apple文檔。
你可以用
NSString rangeOfString:
搜索您的字符串。
有關此內容的更多信息: Apple文檔:搜索字符串
如果您想堅持使用可可,那么NSScanner
是您的朋友。
如果您不想使用普通的unix api,則可以使用:
int match = system("grep -q password123 pathToMyfile");
並檢查match
是否為0,在這種情況下已找到匹配項。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.