C++如何将一个存有数据的文本文件转换为二进制文件?

2025-02-23 01:40:59
推荐回答(4个)
回答1:

这个主要就是把文件读出来,然后换存储方式 读的是("xx.txt","r") 存的时候用("xx.dat","wb") 文件读取最好用纯C的写,C++的文件流操作不是很好,据说微软准备放弃这块了 我也是听老师说的,说C++的文件指针操作的时候经常会乱跑。。 作者可以去了解下C的文件操作

回答2:

#include
#include

int main()
{
FILE *in,*out;
char infile[100],outfile[100];
unsigned char ch,cha,chb;
int i,j,k,size;

printf("输入之前文件名(包括后缀,文件要在放在程序根目录下): \n");
scanf("%s",infile);
printf("转换后存储名(包括后缀): \n");
scanf("%s",outfile);

if ((in=fopen(infile,"rb"))==NULL)
{
printf("Can not open infile!\n");
exit(0);
}

if((out=fopen(outfile,"w"))==NULL)
{
printf("Can not open outfile!\n");
exit(0);
}

size=0;
while(!feof(in))
{
fgetc(in);
size++;
}

printf("%d\n",size);
j=1;
k=0;
rewind(in);
while (k {
k++;
ch=fgetc(in);
cha=(unsigned char)0x80;
for (i=0;i<8;i++)
{
chb=ch&cha;
chb=chb>>7;
fprintf(out, "%d", chb );
ch=ch<<1;
}
if (i==8)
fputc(' ',out);
if (j%4==0)
fputc('\n',out);
j++;
}

fclose(in);
fclose(out);

return 0;
}
上面的

回答3:

c++中采用ifstream ifile("stu.txt")打开源文件,读入数据,再用ofstream ofile("flu.dat",ios::binary)打开二进制文件,使用write(函数写入就可以了)

回答4:

比如
struct A
{
int type;
union Value
{
char chrValue;
struct strBitValue
{
unsigned int bit01:1;
unsigned int bit02:1;
unsigned int bit03:1;
unsigned int bit04:1;
unsigned int filler:4;
} bitVlaue;
} v;
};
然后用fread读入,再用fprintf输出成你想要的格式。