C语言文本文件大小写互换代码失效,请求技术指导
Fixing Your Case-Swapping File Processing Code
Hey there! Let's walk through the issues in your code and fix it step by step so it can properly swap the case of every character in your input file and write the result to an output file.
Key Issues in Your Current Code
Let's break down what's going wrong:
- Missing required headers: You're using
strlen()but haven't included<string.h>, and you'd benefit from<ctype.h>for safer character handling. - Invalid format strings: The
"%[^ ]"infscanfandfprintfis not valid syntax—you meant"%[^\n]", but even that has limitations. - Incomplete case conversion: Your code only turns uppercase letters to lowercase, but you need to swap both ways (lowercase → uppercase too).
- Resource leak: You never close the input file before reusing the
fptrvariable for the output file. - Off-by-one loop error: The condition
i <= strlen(c)processes the null terminator\0, which is unnecessary. - Buffer overflow risk:
fscanfwith%[^\n]can overflow your 1000-byte buffer if the input line is too long.
Corrected Full Code
Here's the fixed version with explanations below:
#include <stdio.h> #include <stdlib.h> #include <string.h> #include <ctype.h> int main() { char c[1000]; FILE *fptr; // Open input file for reading if ((fptr = fopen("text.txt", "r")) == NULL) { printf("Error! opening input file"); exit(1); } // Read safely (up to 999 characters, including newline) if (fgets(c, sizeof(c), fptr) == NULL) { printf("Error reading from file"); fclose(fptr); exit(1); } fclose(fptr); // Close input file immediately after use printf("Data from the file:\n%s", c); // Swap case for each character for (int i = 0; c[i] != '\0'; i++) { if (isupper(c[i])) { c[i] = tolower(c[i]); } else if (islower(c[i])) { c[i] = toupper(c[i]); } // Non-alphabet characters stay as-is } // Open output file for writing if ((fptr = fopen("program.txt", "w")) == NULL) { printf("Error! opening output file"); exit(1); } fprintf(fptr, "%s", c); fclose(fptr); // Close output file return 0; }
What Changed & Why
- Added missing headers:
<string.h>forstrlen()and<ctype.h>forisupper(),tolower(), etc.—these make your code more portable than hardcoding ASCII values. - Used
fgets()instead offscanf:fgets()lets you specify a maximum buffer size, preventing overflow, and it handles newline characters properly. - Fixed case conversion: Now the code swaps both uppercase ↔ lowercase using standard library functions, which works across all systems (not just ones using ASCII).
- Closed files properly: Each file is closed right after we're done with it to avoid resource leaks.
- Improved loop logic: The loop runs until it hits the null terminator
\0, which is more efficient and reliable than checkingstrlen()every iteration.
If you need to process the entire file (not just a single line), we'd adjust the code to read character-by-character instead of using a buffer. Just let me know if you want help with that!
内容的提问来源于stack exchange,提问作者Fatima Noor
相关产品推荐
相关产品推荐

