【发布时间】:2012-02-20 09:01:52
【问题描述】:
我想复制我的二进制文件,但我需要从我的二进制文件的十六进制表示中复制它。
在第一个程序中,我使用二进制文件的十六进制表示创建 txt 文件:
#include <stdio.h>
#include <stdlib.h>
const int BYTE = 1;
int counter = 0;
int read;
long size;
FILE *file1 = NULL;
FILE *file2 = NULL;
fpos_t length;
int main() {
unsigned char hex[3];
unsigned char buffer[1];
file1 = fopen("server.pdf", "rb");
fseek(file1, 0, SEEK_END);
fgetpos(file1, &length);
size = length.__pos;
fseek(file1, 0, SEEK_SET);
if (file1) {
file2 = fopen("test.txt", "w");
while (counter < size) {
read = fread(buffer, 1, BYTE, file1);
counter += read;
i = 0;
while(i<read) {
sprintf(hex, "%02x", (unsigned int) buffer[i++]);
fwrite(hex, 1, BYTE, file2);
}
}
} else
printf("ERROR");
fclose(file1);
fclose(file2);
}
在第二个中,我从 txt 文件中读取数据,然后将其写入二进制文件:
#include <stdio.h>
FILE *file1;
FILE *file2;
int size;
fpos_t length;
int main(){
file1 = fopen("test.txt", "r");
fseek(file1, 0, SEEK_END);
fgetpos(file1, &length);
size = length.__pos;
fseek(file1, 0, SEEK_SET);
char buffer[1];
char hex[3];
int counter = 0;
int read;
if(file1){
file2 = fopen("test.pdf", "wb");
while (counter < size) {
read = fread(hex, 1, 3, file1);
counter += read;
sscanf(hex, "%02x", buffer);
fwrite(buffer, 1, 1, file2);
}
}
fclose(file1);
fclose(file2);
}
很遗憾,我无法打开我的副本。是什么原因?
【问题讨论】:
-
从来没有读过大小 1,这既慢又愚蠢。你有一个缓冲区,填充它并遍历它的内容。
read = fread(buffer, 1, BYTE, file1);count += read;i = 0;while (i < read){ sprintf(hex, "%02x", (unsigned int) buffer[i++]); fwrite(hex, 1, BYTE, file2) } -
另外,这如何编译
char buffer[size];??这是 C ANSI 禁止的,这是什么类型的 C?你为什么不使用 malloc ? -
很抱歉我的C语言不高。我在编译方面没有问题。