不能在C中正确读取带有密码的.txt文件

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

//This is my code: #include  #include  #include  #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; } 

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

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

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

如果您的意思是放置文件的位置而不必指定路径,那么您可以找到以下内容:

 #include  … puts(_getcwd(NULL, 0));