繁体   English   中英

在C中fread fwrite fseek

[英]fread fwrite fseek in C

您好我想要做的是反转二进制文件。 文件的类型是wav,例如,如果通道号是2,每个样本的比特是16,每次我将复制32/8 = 4个字节。 第一个想做的是按原样复制标题(该部分没问题),然后反转数据。 我已经创建了一个代码来复制标题,然后将这部分数据从最后复制10次(用于测试),但是由于某种原因,它不会复制40个字节而是在20处停止(即使它会这样做20次也会仍然只复制20个字节)。 这是执行此操作的代码。 我不能发现错误,如果你能看到它告诉我:)也许错误是在其他地方,所以我写了完整的功能

void reverse(char **array)
{
    int i=0;
    word numberChannels;
    word bitsPerSample;
    FILE *pFile;
    FILE *pOutFile;
    byte head[44];
    byte *rev;
    int count;
    if(checkFileName(array[2]) == 0 || checkFileName(array[3]) == 0)
    {
        printf("wrong file name\n");
        exit(1);
    }
    pFile = fopen (array[2] ,"r");
    fseek(pFile, 22, SEEK_SET);//position of channel
    fread(&numberChannels, sizeof(word), 1, pFile);
    fseek(pFile, 34, SEEK_SET);//position of bitsPerSample
    fread(&bitsPerSample, sizeof(word), 1, pFile);
    count = numberChannels * bitsPerSample;
    rewind(pFile);
    fread(head, sizeof(head), 1, pFile);
    pOutFile = fopen (array[3] ,"w");
    fwrite(head, sizeof(head), 1, pOutFile);
    count = count/8;//in my example count = 32 so count =4
    rev = (byte*)malloc(sizeof(byte) * count);//byte = unsigned char
    fseek(pFile, -count, SEEK_END);
    for(i=0; i<10 ; i++)
    {
        fread(rev, count, 1, pFile);
        fwrite(rev, count, 1, pOutFile);
        fseek(pFile, -count, SEEK_CUR);     
    }
    fclose(pFile);
    fclose(pOutFile);
}

sizeof(rev)将评估指针的大小。 你可能只想用count来代替。

此外,行count = count + count按照您的要求执行? (即双打count每次迭代)

我会改变你的fseek从当前位置相对移动(并使用count而不是sizeof(rev) ):

for(i=0; i<10; i++)
{
    fread(rev, count, 1, pFile);
    fwrite(rev, count, 1, pOutFile);
    fseek(pFile, -count, SEEK_CUR);
}

您需要将count初始化为4并逐步添加4。 另外, sizeof(rev)只是指针的大小(4/8字节)。 您需要使用sizeof(byte) * count 你也可以直接在for中使用count:

pFile = fopen(array[2] ,"r");
pOutFile = fopen(array[3] ,"w");
rev = (byte*)malloc(sizeof(byte) * count); //byte = unsigned char
for(count = 4; count < 44; count += 4)
{
    fseek(pFile, -count, SEEK_END);
    fread(rev, sizeof(byte), count, pFile);
    fwrite(rev, sizeof(byte), count, pOutFile);
}
fclose(pFile);
fclose(pOutFile);

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM