2014-01-23 33 views
1

好的,所以基本上我必須爲一個項目做一個簡單的登錄系統,我決定使用這個文件,並在這裏有一個隨機通用帳戶的小日誌,以及他們的用戶名和密碼。C編程登錄系統:找到用戶名

Apple Password 
Banana abcdefg 
Vader Starwars 
Skywalker jedi 
Chief Weapon 
Gravity Planet 
Lightyear long 
Hammer nail 
Hot-rod car 
Speed fast 
Shield cover 
Tech machine 
Pony My_little 
Cat Alone 
Bro Love 
Banshee Ghast 

現在我發現了一些程序在網上,將搜索字符串,並告訴我這是在哪條線這樣我就可以找到密碼,但是當我下載並運行它,有幾個問題:

#include<stdio.h> 
#include<string.h> 
#include<stdlib.h> 

//Just some function prototypes. 
int Search_in_File(char *str, char *fname); 
void Usage(char *filename); 

//Our main function. 
int main(int argc, char *argv[]) { 
    int result, errno; 

    if(argc < 3 || argc > 3) { 
     Usage(argv[0]); 
     //exit(1); 
     getch(); 
    } 

    //Use system("cls") on windows 
    //Use system("clear") on Unix/Linux 
    system("cls"); 

    result = Search_in_File(argv[1], argv[2]); 
    if(result == -1) { 
     perror("Error"); 
     printf("Error number = %d\n", errno); 
     getch(); 
     //exit(1); 
    } 
    return(0); 
} 

void Usage(char *filename) { 
    printf("fdhjx"); 
} 

int Search_in_File(char *fname, char *str) { 
    FILE *fp; 
    int line_num = 1; 
    int find_result = 0; 
    char temp[512]; 

    //gcc users 
    if((fp = fopen("Student Data base.txt", "r")) == NULL) 
     { 
      return(-1); 
     } 

    /*Visual Studio users 
     if((fopen_s(&fp, fname, "r")) != NULL) { 
     return(-1); */ 
    //} 
    while(fgets(temp, 512, fp) != NULL) { 
     if((strstr(temp, str)) != NULL) { 
      printf("A match found on line: %d\n", line_num); 
      printf("\n%s\n", temp); 
      find_result++; 
     } 
     line_num++; 
    } 

    if(find_result == 0) { 
     printf("\nSorry, couldn't find a match.\n"); 
    } 

    //Close the file if still open. 
    if(fp) { 
     fclose(fp); 
    } 
    return(0); 
} 


/* Bonus 
    /* Below you'll find another way to handle 
    /* files and error-handling using a stream. *\ 

    //FILE *stream = fopen("test.txt", "r"); 
    //if(!stream) { 
    /* Handle error properly here */ 
//return; 
//} 
//fprintf(stream, "Hello world!"); 
//fclose(stream); 

它編譯得很好,但輸出只是崩潰並停止工作,任何人都可以發現問題嗎?

+0

您是否嘗試過使用調試器來弄清楚有什麼問題? – Barmar

+0

您是否實際提供了至少兩個命令行參數? – Nabla

+0

它似乎並沒有崩潰,甚至有趣的地方。 – BLUEPIXY

回答

2

啓用警告編譯告訴我,

warning: implicit declaration of function ‘getch’

getch在控制檯I/O頭conio.h顯然聲明。該getch不是你的程序的核心功能部分,所以

  1. 評論者淘汰(還有system("cls")行我的Mac在運行時不明白)和

  2. 同時提供命令直插式ARGS

給出了一個工作程序:

./zpa fakefilename Sky 
A match found on line: 4 

Skywalker jedi 

請注意,Search_in_File的參數fname未被使用,因此命令行輸入可能會減少爲一個參數。將借來的代碼減少到您需要的最小內核通常對調試事情非常有幫助。