1

我正在尝试分配一个短裤块,将其写入文件,然后将其读回。但是写入文件的数据与输出的数据不匹配。我已将问题隔离为以下代码。任何想法我做错了什么?

#define CHUNK_SIZE 1000
void xwriteStructuresToFile(FILE *file, void * structureData)
{
    assert((fwrite(structureData, sizeof(short), CHUNK_SIZE, file)) == CHUNK_SIZE);

}

void wwbuildPtxFiles(void)
{   
    FILE *file = fopen("s:\\tv\\run32\\junky.bin", WRITE_BINARY);
    int count = 10;
    short *ptx = (short *) calloc(CHUNK_SIZE * count, sizeof(short ) );

    memset(ptx, '3', sizeof(short) * CHUNK_SIZE * count);
    for (int dayIndex = 0; dayIndex < count; ++dayIndex)
        xwriteStructuresToFile(file, (void *) &ptx[ CHUNK_SIZE * sizeof(short) * dayIndex ]);

    free(ptx);
    fclose(file);

    file = fopen("s:\\tv\\run32\\junky.bin", READ_BINARY);
    int xcount = CHUNK_SIZE * count * sizeof(short );
    for (int i = 0; i < xcount; ++i)
    {
        char x;
        if ((x = getc(file)) != '3')
            assert(false);
    }
}
4

5 回答 5

2

从数组索引中删除 sizeof(short)。C会为你做这个计算

于 2012-02-14T05:35:39.293 回答
1

在您对 的调用中xwriteStructuresToFile,您使用:

&ptx[ CHUNK_SIZE * sizeof(short) * dayIndex ]

ptx是一个短指针,意味着数组计算将自动放大到一个短的大小。

通过在上面的表达式中明确地执行此操作,您将远远超出数组的末尾。您需要将该行替换为以下内容:

xwriteStructuresToFile(file, &ptx[CHUNK_SIZE * dayIndex]);
于 2012-02-14T05:33:59.443 回答
1

您正在写入超出数组末尾的“数据”!

xwriteStructuresToFile(file, (void *) &ptx[ CHUNK_SIZE * sizeof(short) * dayIndex ]);

你应该使用:

xwriteStructuresToFile(file, &ptx[CHUNK_SIZE * dayIndex]);

C 编译器会sizeof(short)自动按比例缩放。如果你有一个整数数组,你不会写array[i * sizeof(int)]访问数组的第 i成员;同样,在这里您不需要将索引缩放sizeof(short). 确实,您不这样做是至关重要的,因为您在内存中写入了两次(假设sizeof(short) == 2),因为您预期的内存。

您也不应该assert()在必须执行的函数调用周围使用。您可以assert()在单独的语句中使用该语句,该语句可以从程序中省略而不影响其功能。这在 Steve Maguire 的“Writing Solid Code”中有详细讨论,在某些地方有点过时,但至少在这一点上是合理的。

于 2012-02-14T05:39:40.433 回答
1

一些东西:

您打开文件的方式,我不确定您的常量,但它们应该阅读

"wb"写入二进制文件并"rb"读取。

永远不要在断言中放置语句,当程序以发布模式编译时,断言会被删除。相反,检查返回值并断言

例如


bool ok =fwrite(structureData, sizeof(short), CHUNK_SIZE, file)) == CHUNK_SIZE;
assert(ok);

尽管您不应该对此断言,但您应该打印出正确的错误消息。assert 用于编程错误,而不是运行时错误


short *ptx = (short *) calloc(CHUNK_SIZE * count, sizeof(short ) );

上面的行包含许多问题:

  • calloc永远不要在 C中转换返回值。short *ptx = calloc...如果你收到警告就足够了,#include <stdlib.h>

  • 你应该使用calloc( count, CHUNK_SIZE * sizeof( short ));它否则看起来有点不清楚的表格。( calloc 接受 number,size 作为参数)


   for (int dayIndex = 0; dayIndex < count; ++dayIndex)
      xwriteStructuresToFile(file, 
         (void *) &ptx[ CHUNK_SIZE * sizeof(short) * dayIndex ]);

不知道你在那里做什么,将这两个语句替换为


fwrite( ptx, CHUNK_SIZE * sizeof( short ), count, fp );


那应该写整个数组。

于 2012-02-14T06:15:30.787 回答
0

因为ptx是一个指针,所以你不应该在索引它时short *乘以。sizeof(short)索引已经以shorts 为单位,所以你想要:

xwriteStructuresToFile(file, (void *) &ptx[ CHUNK_SIZE * dayIndex ]);
于 2012-02-14T05:34:37.587 回答