c - 在 C 中未正确读取带有密码的 .txt 文件

标签 c arrays visual-studio file

对于我的代码,我需要创建一个包含用户名(名字)和密码(姓氏)的 .txt 文件。我的代码需要读取该文件。如果我输入了正确的用户名和密码,它会让我登录。如果不正确,它不会让我登录。到目前为止,在我的 name.txt 文件(包含我的用户名和密码的文件)中,我有 Lebron James、Joe Smith。当我运行代码时,我只是在命令提示符中显示“无法打开文件名.txt”。知道我需要对我的代码进行哪些更改吗?

//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?

如果您的意思是在哪里指定现有文件的已知路径,则在文件名之前,例如例如:

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

如果您的意思是在哪里放置文件而不需要指定路径,那么您可以使用 e 找到。例如:

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

关于c - 在 C 中未正确读取带有密码的 .txt 文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40950547/

相关文章:

php计算 explode 后的字符串数

visual-studio - 如何引用 .cpp 文件而不将它们包含在 Visual Studio 的解决方案中?

c - 错误 C2036 : 'void *' : unknown size

javascript - 错误 : Element numerics. 长度不受支持

c - 为什么有这么多结构?

c - 包含标题时未定义的函数引用

c - 与 char *foo[] 的字符串连接

java - 如何随机组合 2 个数组的元素,同时确保在所有元素至少使用一次之前不会重复使用某个元素?

C - 结构 - 不进行强制转换的整数到指针

c++ - ctags 没有索引类成员函数