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

C语言读取文件前3字符报错:country_code变量栈损坏问题排查

Fixing Stack Corruption & Other Bugs in Your Phone Number Validation Code

Hey there! Let’s walk through why you’re hitting that "Stack around the variable 'country_code' was corrupted" error, plus fix other logic bugs to align with your requirements.

1. The Stack Corruption Root Cause

You declared char country_code[3], but when using %3s in fscanf, it reads 3 characters plus a null terminator (\0) to mark the end of the string. That’s 4 bytes total, but your array only has space for 3. Writing past the array bounds corrupts stack memory, triggering the error.

Fix: Increase the array size to fit the null terminator:

char country_code[4]; // 3 chars + 1 null terminator

2. String Comparison Doesn’t Work with ==

In C, country_code == "972" compares memory addresses of the two string pointers, not the actual character content. This will almost always return false, even if the strings look identical.

Fix: Use the strcmp function from <string.h>—it returns 0 when strings match:

if (strcmp(country_code, "972") == 0)

3. Incorrect File Error Check

When opening your output file fp, you’re checking if f == NULL (the input file pointer) instead of fp == NULL. This means you’ll miss errors if the output file fails to open.

Fix: Update the check to target the correct file pointer, and don’t forget to close the input file if the output file fails:

if (fp == NULL) {
    printf("ERROR: Failed to open output file\n");
    fclose(f); // Clean up input file before returning
    return;
}

4. Misusing feof Leads to Invalid Data

Using while (!feof(f)) runs the loop one extra time after reaching the end of the file, because feof only returns true after you attempt to read past the file’s end. This can lead to processing garbage data.

Fix: Restructure the loop to check if the fscanf read was successful directly:

int read_result;
while ((read_result = fscanf(f, "%3s %s", country_code, num)) == 2) {
    // Process valid data here
}

5. Aligning Logic with Your Requirements

Your goal is to write only 12-digit numbers starting with 972 (like 9725XXXXXXXX). Your original code checks if strlen(num) == 12, which would create a 15-digit full number (3 + 12), which doesn’t match your needs.

Assuming your input file splits lines into country code and number suffix (e.g., 972 5XXXXXXXX), the suffix needs to be 9 digits to make a 12-digit full number. Here’s the adjusted condition:

if (strcmp(country_code, "972") == 0 && strlen(num) == 9) {
    fprintf(fp, "%s%s\n", country_code, num); // Concatenate and write full number
}

If your input file has full phone numbers per line (e.g., 9725XXXXXXXX), use this version instead (reads entire lines and checks length/prefix):

#include <stdio.h>
#include <string.h>

void fix_file_il_country(char *filename) {
    FILE *f = fopen("1.txt", "r");
    if (f == NULL) {
        printf("ERROR: Failed to open input file\n");
        return;
    }

    FILE *fp = fopen(filename, "w");
    if (fp == NULL) {
        printf("ERROR: Failed to open output file\n");
        fclose(f);
        return;
    }

    char full_num[13]; // 12 digits + null terminator
    while (fgets(full_num, sizeof(full_num), f) != NULL) {
        // Remove newline character from the end of the line
        full_num[strcspn(full_num, "\n")] = '\0';

        // Check for exact 12-digit length and 972 prefix
        if (strlen(full_num) == 12 && strncmp(full_num, "972", 3) == 0) {
            fprintf(fp, "%s\n", full_num);
        }
    }

    fclose(f);
    fclose(fp);
}

Full Fixed Code (Split Input Format)

Here’s the complete corrected code for when your input lines are split into country code and suffix:

#include <stdio.h>
#include <string.h>

void fix_file_il_country(char *filename) {
    // Open input file
    FILE *f = fopen("1.txt", "r");
    if (f == NULL) {
        printf("ERROR: Failed to open input file\n");
        return;
    }

    // Open output file
    FILE *fp = fopen(filename, "w");
    if (fp == NULL) {
        printf("ERROR: Failed to open output file\n");
        fclose(f);
        return;
    }

    char country_code[4]; // 3 chars + null terminator
    char num[10]; // Holds 9-digit suffix (plus null terminator)
    int read_result;

    // Read lines while both country code and number are successfully read
    while ((read_result = fscanf(f, "%3s %s", country_code, num)) == 2) {
        // Validate country code and suffix length for 12-digit full number
        if (strcmp(country_code, "972") == 0 && strlen(num) == 9) {
            fprintf(fp, "%s%s\n", country_code, num);
        }
    }

    // Check if read failed due to an error (not just end of file)
    if (read_result != EOF) {
        printf("ERROR: Failed to read from input file\n");
    }

    // Clean up file pointers
    fclose(f);
    fclose(fp);
}

内容的提问来源于stack exchange,提问作者Roy Raihenshtein

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.29 09:03:30