C语言实现用户名密码文件匹配及文件打开失败问题解决
解决C语言文件匹配写入中的"cannot open file"问题及完整实现
Hey there! Let's tackle this problem step by step—first fixing that annoying "cannot open file" error, then getting the username-password matching and writing working smoothly using fread and fwrite as you mentioned.
首先排查"cannot open file"的常见原因
Before diving into code, let's rule out the most common reasons for this error:
- Incorrect file path: If your
username.txt/password.txtaren't in the same folder as your compiled program, you need to use the full absolute path (e.g.,C:\projects\username.txton Windows,/home/you/projects/username.txton Linux/macOS) or correct relative path. - Permission issues: Make sure the files are readable (you're not trying to access a restricted system file) and the directory where you want to write the output file has write permissions.
- Typos in filenames: Double-check for spelling mistakes, extra spaces, or case sensitivity (Linux/macOS care about uppercase/lowercase, Windows doesn't).
完整实现代码
Here's a complete, tested program that uses bulk I/O with fread/fwrite, handles file opening errors properly, and matches the 20 usernames/passwords (assuming they're in order—each line in username.txt corresponds to the same line in password.txt):
#include <stdio.h> #include <stdlib.h> #include <string.h> #ifdef _WIN32 #include <direct.h> // For _getcwd() on Windows #else #include <unistd.h> // For getcwd() on Linux/macOS #endif // Define a struct to hold each username-password pair #define MAX_LEN 50 typedef struct { char username[MAX_LEN]; char password[MAX_LEN]; } Credential; int main() { // Optional: Print current working directory to verify file path char cwd[1024]; #ifdef _WIN32 if (_getcwd(cwd, sizeof(cwd)) != NULL) { #else if (getcwd(cwd, sizeof(cwd)) != NULL) { #endif printf("Current working directory: %s\n", cwd); } else { perror("Failed to get current directory"); } FILE *user_fp, *pass_fp, *out_fp; Credential users[20], passes[20], combined[20]; // Open username file for reading (binary mode for reliable bulk I/O) user_fp = fopen("username.txt", "rb"); if (user_fp == NULL) { perror("Failed to open username.txt"); exit(EXIT_FAILURE); } // Open password file for reading pass_fp = fopen("password.txt", "rb"); if (pass_fp == NULL) { perror("Failed to open password.txt"); fclose(user_fp); // Clean up already opened files exit(EXIT_FAILURE); } // Open output file for writing out_fp = fopen("credentials.txt", "wb"); if (out_fp == NULL) { perror("Failed to open credentials.txt"); fclose(user_fp); fclose(pass_fp); exit(EXIT_FAILURE); } // Bulk read 20 usernames size_t user_count = fread(users, sizeof(Credential), 20, user_fp); if (user_count != 20) { printf("Warning: Read only %zu usernames (expected 20)\n", user_count); } // Bulk read 20 passwords size_t pass_count = fread(passes, sizeof(Credential), 20, pass_fp); if (pass_count != 20) { printf("Warning: Read only %zu passwords (expected 20)\n", pass_count); } // Match usernames and passwords (one-to-one order) for (int i = 0; i < 20; i++) { strncpy(combined[i].username, users[i].username, MAX_LEN); strncpy(combined[i].password, passes[i].password, MAX_LEN); // Ensure strings are null-terminated (in case file data isn't) combined[i].username[MAX_LEN - 1] = '\0'; combined[i].password[MAX_LEN - 1] = '\0'; } // Bulk write combined credentials to output file size_t write_count = fwrite(combined, sizeof(Credential), 20, out_fp); if (write_count != 20) { printf("Warning: Wrote only %zu credentials (expected 20)\n", write_count); } // Clean up: Close all files fclose(user_fp); fclose(pass_fp); fclose(out_fp); printf("Success! Credentials written to credentials.txt\n"); return 0; }
关键代码说明
- Struct definition: Using a
Credentialstruct makes bulk reading/writing straightforward—each read/write operation handles an entire username-password pair at once. - Error handling: We use
perror()to print specific system-level error messages (e.g., "No such file or directory" instead of just "cannot open file"), which makes debugging way easier. - Binary mode: Using
"rb"/"wb"instead of text mode ("r"/"w") ensures consistent behavior across operating systems, especially when dealing with bulk data. - Null termination: We explicitly null-terminate the strings to avoid garbage characters if the input files don't properly terminate each line.
如果还是遇到文件打开错误
If you still get the error after checking the basics:
- Use the current working directory output (in the code) to confirm your program is looking in the right folder.
- On Linux/macOS, run
ls -lin that directory to check file existence and permissions. - On Windows, check if the files are marked as "Read-only" (right-click > Properties) or if your antivirus is blocking access.
内容的提问来源于stack exchange,提问作者matteociccozzi
相关产品推荐
相关产品推荐

