c/c++读取二进制文件,并在屏幕上显示内容。
发布网友
发布时间:2023-07-31 18:46
我来回答
共2个回答
热心网友
时间:2023-08-16 16:46
#include <stdio.h> //标准输入输入出的头文件,printf和scanf都在这里了
#include <stdlib.h> //标准库头文件,内存分配、数*算等都在这里了
#define MAXLEN 1024
int main(int argc, char *argv[])
{
if( argc < 3 )
{
printf("usage: %s %s/n", argv[0], "infile outfile");
exit(1);
}
FILE * outfile, *infile;
outfile = fopen(argv[2], "wb" );
infile = fopen(argv[1], "rb");
unsigned char buf[MAXLEN];
if( outfile == NULL || infile == NULL )
{
printf("%s, %s",argv[1],"not exit/n");
exit(1);
}
int rc;
while( (rc = fread(buf,sizeof(unsigned char),MAXLEN,infile)) != 0 )
{
fwrite( buf, sizeof( unsigned char ), rc, outfile );
}
fclose(infile);
fclose(outfile);
return 0;
}追问输入到文件中还是显示乱码,我想的是把那些16进制数字输入文件中,可以做到吗?
热心网友
时间:2023-08-16 16:46
#include <stdio.h>
#include <stdlib.h>
int main(int argc, char *argv[])
{
FILE * fp;
char * pbuf;
long fsize = 0;
int i = 0;
int newline = 0;
//printf("argc = %d, filename = %s\n", argc, argv[1]);
if(argc != 2)
{
printf("usage: ./mp filename\n");
return 1;
}
fp = fopen(argv[1], "rb");
if(!fp)
{
perror("error ");
return 2;
}
fseek(fp, 0, SEEK_END);
fsize = ftell(fp);
fseek(fp, 0, SEEK_SET);
pbuf = (char *)malloc(fsize);
if(NULL == pbuf)
{
printf("malloc failed!\n");
return 3;
}
fread(pbuf, 1, fsize, fp);
while(i < fsize)
{
printf("%3x", pbuf[i]);
i++;
if(++newline == 16)
{
printf("\n");
newline = 0;
}
}
printf("\n");
free(pbuf);
fclose(fp);
return 0;
}