C语言文件处理求助:提取含指定单词的行写入Exit.txt出错
Fixing Your File Processing Code in C
Hey there! I see you're getting started with file handling in C and running into some frustrating issues with your program. Let's walk through what's going wrong and fix it step by step so you can get the result you want.
First, let's break down the key problems in your current code:
- Incorrect matching logic:
strcmp(rez, word) == 0checks if the entire line is exactly equal to your target word, not if the word exists anywhere in the line. You need a different approach to detect substrings. - Overwriting the output file repeatedly: You're opening
Exit.txtwithwtmode inside the loop. This mode clears the file every time you open it, so only the last matching line gets saved in the end. - Unsafe input with
gets(): Thegets()function is risky because it doesn't limit input length, which can cause buffer overflows. We'll replace this with a safer alternative. - Flawed loop condition with
feof(): Usingwhile (!feof(fis))can lead to an extra iteration where you read a NULL line, which might cause crashes or unexpected behavior. - Not closing the output file: You never close
fis2after writing, which can leave data unflushed to the file and waste system resources.
Here's the corrected code:
#include<stdio.h> #include<stdlib.h> #include<string.h> int main() { FILE* fis, * fis2; char* sir, word[50]; printf("Word: "); // Use fgets instead of gets for safe input handling if (fgets(word, sizeof(word), stdin) != NULL) { // Remove the trailing newline added by fgets word[strcspn(word, "\n")] = '\0'; } sir = malloc(50 * sizeof(char)); if (sir == NULL) { printf("Memory allocation failed!"); return 1; } // Open input file fis = fopen("In.txt", "rt"); if (fis == NULL) { printf("Can't open input file!"); free(sir); return 1; } // Open output file ONCE before processing lines (wt mode clears existing content) fis2 = fopen("Exit.txt", "wt"); if (fis2 == NULL) { printf("Can't open output file!"); fclose(fis); free(sir); return 1; } // Correct loop: read lines until fgets returns NULL (end of file or error) while (fgets(sir, 50, fis) != NULL) { // Check if the word exists in the current line using strstr if (strstr(sir, word) != NULL) { // Write the matching line to output file fputs(sir, fis2); } } // Clean up: close all files and free allocated memory fclose(fis); fclose(fis2); free(sir); return 0; }
Let's go over the key changes:
- Safe input with
fgets(): We usefgets()to read the target word, then remove the trailing newline character (added when you press enter) withstrcspn()to avoid unexpected matching issues. - Open output file once: By opening
Exit.txtbefore the loop, we avoid overwriting it every time a match is found. Useatmode instead ofwtif you want to append to an existing file instead of replacing it. - Substring matching with
strstr():strstr(sir, word)returns a pointer to the first occurrence of your target word in the line, or NULL if it's not found. This is exactly what we need to check if the line contains the word. - Proper loop condition: The loop runs as long as
fgets()successfully reads a line (returns non-NULL), which handles end-of-file correctly without extra iterations. - Better error handling: We added checks for memory allocation and file opening failures, making sure to clean up resources (close files, free memory) before exiting if something goes wrong.
- Closing the output file: Always close files after use to ensure all data is written to disk and system resources are released properly.
This should now correctly write all lines from In.txt that contain your target word into Exit.txt!
内容的提问来源于stack exchange,提问作者user14074667
相关产品推荐
相关产品推荐

