【问题标题】:Why is the output file corrupt / filled with garbage? (Expecting numbers)为什么输出文件损坏/充满垃圾? (期待数字)
【发布时间】:2012-01-02 08:36:33
【问题描述】:

以下代码行将 unsigned int 值写入文件,但文件内容不可读。

struct rabin_polynomial
{
    uint64_t start;
    uint16_t length;
    struct rabin_polynomial *next_polynomial;   
};

fprintf(out_file, "%llu,%u",poly->start,poly->length);

如果我将代码的输出显示在命令行屏幕上,它是可读的。

文件“out_file”未以二进制模式打开。

这里是输出文件的部分内容:

 -ÍÍÍÍÍÍp\y";^æó r\ ÍÍÍÍ-       ÍÍÍÍÍÍ
Øâˆ¿»Iðr\ ÍÍÍÍ-      wÍÍÍÍÍÍ7OT-OØÚ‚\ ÍÍÍͤ*      L ÍÍÍÍÍÍî›ùçÉç`‚\ ÍÍÍÍð3       ÍÍÍÍÍÍ
Øâˆ¿»I°‚\ ÍÍÍÍðC       ÍÍÍÍÍÍíK¬è‹Ç{ ƒ\ ÍÍÍÍðS      •   ÍÍÍÍÍÍ-Ló3lJ–ÞPƒ\ ÍÍÍÍ…] 

这是预期的输出:

0,2861 
2861,4096 
6957,3959 
10916,2380 
13296,4096 
17392,4096 

【问题讨论】:

  • 两个数字都无法读取,还是只有其中一个?
  • 请包括相应的文件内容/文件十六进制转储以及所述输出的预期值。首先/也将它们扔到标准输出可能是最简单的。
  • @JoachimPileborg 我已经发布了部分输出
  • @pst:我已经发布了部分输出

标签: c io printf


【解决方案1】:

如果您没有得到您期望的文本值,可能归结为您使用了不正确的格式说明符(我假设您已填充 em> 您尝试在此处打印的变量,但您可能需要确认这一点)。

%llu 明确表示unsigned long long int,其宽度不一定与uint64_t 相同。

在 C99 中,inttypes.h 具有用于格式说明符的宏,可用于精确宽度和 -at-least-as-wide-as 数据类型。

例如:

uint64_t xyzzy = 42;
printf ("Number is: %" PRIu64 "\n", xyzzy);

在这种情况下,PRIu64 表示 printf 格式说明符,无符号十进制输出,用于 ​​64 位精确宽度变量。对于不同的输出类型,还有各种各样的其他类型,以及 scanf 系列的等价物(以 SCN 开头)。

C99 的7.8.1 Macros for format specifiers 部分详细列出了它们。


根据您的更新,您没有得到不正确的数字,而是得到了只能被描述为垃圾的信息,我想说您的问题出在其他地方。即使指针或数据损坏,我也不希望 fprintf 为数字格式字符串生成非数字数据。这当然是可能的,因为它是未定义的行为,但不太可能。

可以得到字符串的那种输出,但这里不是这样。

换句话说,我认为您必须在代码中的其他地方寻找(例如)内存损坏问题。

您可以做的一件事来测试问题是否存在于您认为的行中,将其更改为:

printf("DEBUG: %llu,%u\n",poly->start,poly->length);
fprintf(out_file, "%llu,%u",poly->start,poly->length);

看看终端上会出现什么。

【讨论】:

  • inttypes.h 的宏中不包含“%”,因此它必须仍然在格式字符串中。
【解决方案2】:

您可能需要分享您的代码的读写部分,以便我们为您提供帮助。但看看写入输出文件的内容,fprintf()fscanf() 中的格式说明符似乎存在问题。

以下程序可以作为参考。

#include <stdio.h>
#include <stdlib.h>

#define LEN 6

int main(void)
{
    unsigned long long start[LEN] = {0, 2861, 6957, 10916, 13296, 17392};
    unsigned short int length[LEN] = {2861, 4096, 3959, 2380, 4096, 4096};
    int i;
    unsigned long long s;
    unsigned short int l;
    FILE *out_file, *in_file;

    if ((out_file = fopen("out_file", "w")) == NULL) {
        printf("ERROR: unable to open out_file\n");
        return -1;
    }

    for (i=0; i<LEN; i++)
        fprintf(out_file, "%llu,%hu \n",start[i], length[i]);

    fclose(out_file);


    if ((in_file = fopen("out_file", "r")) == NULL) {
        printf("ERROR: unable to open out_file\n");
        return -1;
    }

    for (i=0; i<LEN; i++) {
        fscanf(out_file, "%llu,%hu \n", &s, &l);
        printf("start = %llu - length = %hu \n", s, l);
    }

    fclose(in_file);

    return 0;
}

请注意fscanf()fprintf() 中的format(第二个参数)必须分别与readingwriting 行匹配。

【讨论】:

    【解决方案3】:

    请用十六进制编辑器检查文件内容并与多结构的实际值进行比较。

    你会看到问题所在。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-08-08
      • 1970-01-01
      • 2021-03-05
      • 2018-09-12
      • 2021-11-02
      • 1970-01-01
      • 2015-01-15
      • 1970-01-01
      相关资源
      最近更新 更多