0

Hi I'm building an app which will check the numbers in the file are all fixed, and if not - to fix them (Depending on specific country codes). In order to check if the number is good I first need to look at the country code, and for that I need to read the first 3 chars (From a phone number in file) to see if the number even have a country code. When I'm running the code below I'm getting

Stack around the variable 'country_code' was corrupted".

I think my reading the specific 3 char from the string is making the problem, but I can't find what exactly is doing it.

void fix_file_il_country(char *filename)
{
    FILE *f = fopen("1.txt", "r");                  //The file to check from
    if (f == NULL)
    {
        printf("EROR\n");
        return;
    }
    FILE *fp = fopen(filename, "w");                //The new file with fixed numbers
    if (f == NULL)
    {
        printf("EROR\n");
        return;
    }
    char num[20];
    char country_code[3];
    fscanf(f, "%3s %s", &country_code, &num);
    while (!feof(f))
    {
        if (strlen(num) == 12)
            if (country_code == "972")
                fprintf(fp, "%s\n", num);
        fscanf(f, "%3s %s", &country_code, &num);
    }
    fclose(f);
    fclose(fp);
}

The numbers like: 9725XXXXXXXX should be written the new file Numbers like: 123XXXXXXXXX, or number with more\less chars than 12 shouldn't been written.

2 Answers2

1

You haven't provided space for the null terminator.

char country_code[3];

should be

char country_code[4];

Also, see Why is “while ( !feof (file) )” always wrong?

Barmar
  • 741,623
  • 53
  • 500
  • 612
1

I can see two potential issues:

  1. the char array needs to store also the null termination, so it should be defined as

    char country_code[4]
    

    otherwise it is not possible to define the end of the array.

  2. In the scanf you are passing the pointer of a pointer. You should change

    fscanf(f, "%3s %s", &country_code, &num)
    

    to

    fscanf(f, "%3s %s", country_code, num)
    

    without the &.