关于C语言读取txt文件数据
请教一下大家:怎样读取一个txt文件里面的16进制的数据,例如:13 12 AA
将这些数据读取后,写入另一个bin文件中呢。
现在我写的只能读取十进制的数据。
while (1) {
if (1!=fscanf(fp_data,"%x",&v)) break;
fwrite(&v,1,1,fp_txt);
}
fp_data ,和fp_txt都是文件指针;
[解决办法]
# include <stdio.h>
int main()
{
FILE * input_file = fopen("input", "r");
FILE * output_file = fopen("output", "wb");
int i;
char c;
while (fscanf(input_file, "%x", &i) != EOF)
{
c = i;
fwrite(&c, 1, 1, output_file);
}
fclose(input_file);
fclose(output_file);
return 0;
}
[解决办法]
#include <stdio.h>
#include <string.h>
#include <conio.h>
FILE *fi,*fo;
int r;
unsigned int n,c;
//-------------------------------------------------------
void main(int argc,char *argv[])
{
if (argc<3) {
cprintf("Hex2Bin srcfile desfile");
return;
}
if ((fi=fopen(argv[1],"r"))==NULL) {
cprintf("Can not find file %s",argv[1]);
return;
}
if ((fo=fopen(argv[2],"wb"))==NULL) {
fclose(fi);
cprintf("Can not create file %s",argv[2]);
return;
}
n=0;
while (1) {
r=fscanf(fi,"%2x",&c);
if (EOF==r) break;//
if (1==r) {
fputc(c,fo);
n++;
} else {
r=fgetc(fi);
if (EOF==r) break;//
}
}
fcloseall();
cprintf("OK to Hex2Bin %d bytes.",n);
}