gpt4 book ai didi

c - 逐 block 反转文件内容

转载 作者:太空宇宙 更新时间:2023-11-04 10:30:13 29 4
gpt4 key购买 nike

这是一个逐 block 反转文件内容的程序。

#include <stdio.h>
#include <stdlib.h>
#define BS 12

void reverse(char * buffer, int size)
{
char tmp;
int i;
for(i = 0; i < size / 2; i++)
{
tmp = (char)buffer[i];
buffer[i] = buffer[size - i - 1];
buffer[size - i - 1] = tmp;
}
}

int main (const int argc, const char** argv)
{
if(argc != 3)
exit(-1);

char * buffer = malloc(BS);
FILE * f1, * f2;
f1 = fopen(argv[1], "r");
f2 = fopen(argv[2], "w");

fseek(f1, 0, SEEK_END);

long i = ftell(f1);
// long f1_len = ftell(f1);
// unsigned char tmp;
int if_end = 1;
int need = 0;
int count;


do
{
i = i - BS;
if(i < 0)
{
need = BS - abs(i);
i = 0;
}
else
need = BS;

fseek(f1, i, SEEK_SET);

if(if_end) // strip EOF
{
count = fread(buffer, need - 1, 1, f1);
if_end = 0;
}
else
count = fread(buffer, need, 1, f1);

reverse(buffer, count);
fwrite(buffer, count, 1, f2);

if(i == 0)
break;
}while(i > 0);


fclose(f1);
fclose(f2);
free(buffer);

return 0;
}

测试文件:

$ xxd testfile
0000000: 6162 6364 6566 670a abcdefg.
$ gcc test.c -o test
$ ./test testfile testfile2
$ xxd testfile2
0000000: 61 a

知道哪里错了吗?我已经调试了很长时间。

最佳答案

你的问题是 fwrite 返回成功 block 的数量,而不是字节数。

所以reverse(buffer, count);需要是reverse(buffer,count * need)

同样,写入输出需要是fwrite(buffer, count * need, 1, f2);

关于c - 逐 block 反转文件内容,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40317885/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com