【问题标题】:Not reading my .txt file with passwords correctly in C没有在 C 中正确读取带有密码的 .txt 文件
【发布时间】:2016-12-03 17:31:42
【问题描述】:

对于我的代码,我需要制作一个包含用户名(名字)和密码(姓氏)的 .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;
}

【问题讨论】:

标签: c arrays visual-studio file


【解决方案1】:

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

如果您的意思是在哪里指定现有文件的已知路径,那么就在文件名之前,例如。 g.:

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

如果您的意思是无需指定路径而将文件放在哪里,那么您可以使用 e 查找。 g.:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2022-12-30
    • 2022-01-21
    • 1970-01-01
    • 2023-02-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多