【问题标题】:I'm trying to read only the first 3 chars from a file - c我正在尝试仅从文件中读取前 3 个字符 - c
【发布时间】:2018-06-01 07:37:45
【问题描述】:

您好,我正在构建一个应用程序,它将检查文件中的数字是否全部固定,如果没有 - 修复它们(取决于特定的国家代码)。 为了检查号码是否正确,我首先需要查看国家代码,为此我需要读取前 3 个字符(来自文件中的电话号码)以查看该号码是否有国家代码。 当我运行下面的代码时,我得到了

围绕变量“country_code”的堆栈已损坏”。

我认为我从字符串中读取特定的 3 个字符是有问题的,但我找不到到底是在做什么。

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);
}

像这样的数字:9725XXXXXXXX 应该写入新文件 不应写入诸如 123XXXXXXXXX 之类的数字,或字符数多于/少于 12 个的数字。

【问题讨论】:

  • 请显示一些样本输入和所需输出对。将其与您实际获得的输出进行对比。
  • 请将您的代码报价升级为minimal reproducible example
  • 此外,数组衰减为指向第一个元素的指针,因此 fscanf(f, "%3s %s", country_code, num);

标签: c string file


【解决方案1】:

您没有为空终止符提供空间。

char country_code[3];

应该是

char country_code[4];

另外,请参阅Why is “while ( !feof (file) )” always wrong?

【讨论】:

    【解决方案2】:

    我可以看到两个潜在的问题:

    1. char 数组还需要存储空终止符,因此应定义为

      char country_code[4]
      

      否则无法定义数组的结尾。

    2. scanf 中,您传递的是指针的指针。你应该改变

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

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

      没有&

    【讨论】:

    • 正如上面的两个评论所说,我需要在字符串中添加另一个空格才能工作。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-01-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-01-09
    相关资源
    最近更新 更多