【发布时间】: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;
}
【问题讨论】:
-
t未定义fopen的标志,因此函数失败,errno应为EINVAL。 -
如果您无法打开该文件,则说明该文件位于错误的位置或您的工作目录不正确。
-
@Jean-BaptisteYunès 在 Visual Studio 中有效。 msdn.microsoft.com/en-us/library/yeby3zcb(v=vs.140).aspx
-
@RetiredNinja 文件应该放在哪里?
-
工作目录默认为项目所在的位置,因此请将文件复制到那里或更改工作目录。 stackoverflow.com/questions/21499391/…
标签: c arrays visual-studio file