You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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) == 0 checks 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.txt with wt mode 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(): The gets() 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(): Using while (!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 fis2 after 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:

  1. Safe input with fgets(): We use fgets() to read the target word, then remove the trailing newline character (added when you press enter) with strcspn() to avoid unexpected matching issues.
  2. Open output file once: By opening Exit.txt before the loop, we avoid overwriting it every time a match is found. Use at mode instead of wt if you want to append to an existing file instead of replacing it.
  3. 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.
  4. 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.
  5. 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.
  6. 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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.08 19:02:43