C++命令行文件复制程序:新文件创建后无法写入及多文件异常
Let's walk through the issues in your code one by one and get things working correctly:
Key Problems Identified
1. Main Function Parameter Mix-Up
You swapped the names of main's parameters! The first parameter is argc (count of command-line arguments), and the second is argv (array of argument strings). Your code uses int argv, const char* argc[], which breaks the loop that processes target files. Plus, you hardcoded i < 10 instead of using argc to iterate over all provided target files—this is why you couldn't process multiple missing files.
2. Broken Exit Logic in WriteFile
The second while loop in WriteFile has a fatal logical error:
while (input.at(0) != 'Y' || input.at(0) != 'y' || input.at(0) != '1') { exit(0); }
This condition is always true—no character can be equal to Y, y, and 1 at the same time. So even if the user chooses to create the file, this loop runs and exits the program immediately, skipping the content write step.
Additionally, you used a while loop for the user input check when a single if is sufficient (the user only needs to answer once).
3. Unchecked File Pointer After Creation
If file creation fails, fptr remains nullptr, but the code still tries to write to it, which will cause a crash.
Fixed Code
Here's the corrected version with all issues addressed:
#include <iostream> #include <cstdio> #include <string> #include <cstdlib> char* ReadFile(const char* filename) { // Assume this function works correctly as stated static char buffer[1024]; // Example placeholder, adjust size as needed FILE* f = fopen(filename, "r"); if (f) { fread(buffer, 1, sizeof(buffer)-1, f); buffer[sizeof(buffer)-1] = '\0'; fclose(f); } return buffer; } void WriteFile(const char* filename, const char* data) { if (!data) { std::cout << "Error: No data to write to " << filename << std::endl; return; } FILE* fptr = fopen(filename, "r+"); if (fptr) { std::cout << filename << " opened successfully.\n"; } else { std::cout << "\nFile " << filename << " not found! Do you want to create one?\n"; std::cout << "Type Y, y or 1 to create, any other key to exit\n"; std::string input; std::cin >> input; // Exit if user doesn't want to create the file if (input.at(0) != 'Y' && input.at(0) != 'y' && input.at(0) != '1') { std::cout << "Exiting without creating " << filename << std::endl; exit(0); } // Attempt to create the file fptr = fopen(filename, "w"); if (!fptr) { std::cout << "Error creating " << filename << std::endl; return; } std::cout << filename << " created successfully\n"; } // Write data only if file pointer is valid if (fptr) { while (*data) { fputc(*data, fptr); ++data; } if (fclose(fptr) == 0) { std::cout << filename << " closed successfully\n"; } else { std::cout << "Error closing " << filename << std::endl; } } } int main(int argc, char* argv[]) { // Validate input arguments if (argc < 3) { std::cout << "Usage: " << argv[0] << " <source-file> <target-file1> [target-file2] ...\n"; return 1; } const char* fileBuffer = ReadFile(argv[1]); if (!fileBuffer) { std::cout << "Error reading source file " << argv[1] << std::endl; return 1; } // Process all target files sequentially for (int i = 2; i < argc; ++i) { WriteFile(argv[i], fileBuffer); } return 0; }
What Changed?
- Fixed Main Parameters: Corrected
argcandargvnames, and now loop over all target files usingi < argcinstead of a hardcoded limit. Added a usage prompt if the user runs the program with too few arguments. - Rewrote User Input Logic: Replaced the broken
whileexit check with a singleifstatement using&&instead of||, so the program only exits if the user doesn't want to create the file. - Added Safety Checks: Added checks for
databeing null andfptrbeing valid before writing, preventing crashes from invalid pointers. - Cleaned Up Flow: Simplified the file creation logic to avoid unnecessary loops, making the code easier to follow.
Now when you run main.exe file.txt todo.txt app.txt foo.txt:
- Existing target files will have their contents overwritten with the source file data.
- Missing target files will prompt the user to create them, and if confirmed, the source data will be written to the new file.
- All target files (existing or new) will be processed in sequence.
内容的提问来源于stack exchange,提问作者Juned Khan

