无法在C中使用密码正确读取我的.txt文件 [英] Not reading my .txt file with passwords correctly in C

查看:45
本文介绍了无法在C中使用密码正确读取我的.txt文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

对于我的代码,我需要制作一个.txt文件,其中包含用户名(名字)和密码(姓氏).我的代码需要读取该文件.如果输入了正确的用户名和密码,它将使我登录.如果输入不正确,则它将不使我登录.到目前为止,在我的name.txt文件(包含用户名和密码的文件)中,我有Lebron James,Joe Smith.当我运行代码时,我只是得到无法打开文件名.txt"以显示在命令提示符下.对我需要对代码进行哪些更改有任何想法吗?

For my code I need to make a .txt file containing a username (first name) and a password (last name). My code needs to read that file. If I entered the correct user name and password it will log me in. If it is incorrect it not log me in. So far in my name.txt file (the file containing my usernames and passwords) I have Lebron James, Joe Smith. As I run my code i just get "could not open file names.txt" to display in the command prompt. Any idea on what changes i need to make to my code?

//This is my code:
#include <stdlib.h> 
#include <string.h> 
#include <stdio.h> 
#define MAX_USER 32 

void get_input(const char *pszPrompt, char *cpszWord, const size_t iLength)
{
while (1) {
    printf("%s> ", pszPrompt);
    if (fgets(cpszWord, iLength * sizeof(char), stdin)) {
        break;
    }
}
size_t iLen = strlen(cpszWord);
if (cpszWord[iLen - 1] == '\n')
    cpszWord[iLen - 1] = 0;
}

int compare(FILE *f, const char *szUser, const char *szPassword)
{
int iFound = 0;
char szName[MAX_USER], szPW[MAX_USER];
while (!feof(f) && iFound != 2) {
    iFound = 0;
    if (fscanf(f, "%s %s", szName, szPW) == 2) {
        if (!strcmp(szName, szUser)) {
            ++iFound;
        }
        if (!strcmp(szPassword, szPW)) {
            ++iFound;
        }
    }
}
return iFound;
}

int main()
{
const char szFile[] = "names.txt";
char user[MAX_USER], password[MAX_USER];
int iFound = 0;
do {
    FILE *f = fopen(szFile, "rt");
    if (!f) {
        printf("Could not open file %s\n", szFile);
        break;
    }
    get_input(" User", user, sizeof(user));
    get_input("Password", password, sizeof(password));
    iFound = compare(f, user, password);
    fclose(f);
    if (iFound == 1) {
        printf("Wrong Password!\n");
    }
} while (iFound && iFound < 2);
if (iFound == 2) {
    printf("Welcome User!\n");
}



system("pause");
return 0;
}

推荐答案

有人知道我应该把它正在读取的文件的位置放在哪里吗?

anyone know where i should put the location of the file that it is reading?

如果要在哪里指定现有文件的已知路径,则在文件名之前,即e.g.:

If you mean where to specify a known path to your existing file, then just before the filename, e. g.:

const char szFile[] = "C:/Users/Public/Documents/names.txt";

如果您的意思是在无需指定路径的情况下将文件放置在何处,则可以使用e查找.g.:

If you mean where to put your file without having to specify a path, then you can find out with e. g.:

#include <direct.h>
…
    puts(_getcwd(NULL, 0));

这篇关于无法在C中使用密码正确读取我的.txt文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆