我无法从二进制文件复制并写入文本文件。我编写了一个程序,它能够从文本文件中复制并写入二进制文件,但我不能反过来。
这是我的功能,我遇到了问题:
void CopyBin2Text(char* rafname, char* txtname)
{
FILE * fraf = fopen(rafname,"rb");
FILE * ftxt = fopen(txtname,"r+");
//READ FROM BINARY FILE
struct PERSON p;
int ByteOfBin;
printf("ID \t NAME \t\t BALANCE \n");
printf("---------------------------------------\n");
当我运行我的程序时,它会在打印上述语句后停在此处
while(!feof(fraf))
{
fscanf(fraf, "%d %s %f", &p.ID, p.name, &p.balance);
ByteOfBin = ((p.ID/10-1)*sizeof(p));
fseek(ftxt,ByteOfBin, SEEK_SET);
fwrite((char *)&p, sizeof(p), 1, ftxt);
}
fclose(fraf);
fclose(ftxt);
}
我注意到的另一个问题是文本文件变得很大而无法打开。结果是我必须删除文本文件并再次创建它。 谁能解释导致这种情况发生的原因?
答案 0 :(得分:3)
我对您的功能进行了一些更改。文件打开模式,检查它们是否打开,转储feof()
,使用适当的二进制和文本函数进行读写,并返回函数是否正常运行的状态。
#include <stdio.h>
#include <string.h>
struct PERSON {
int ID;
char name[20];
float balance;
};
int CopyBin2Text(char* rafname, char* txtname) // changed return value
{
FILE *fraf, *ftxt;
struct PERSON p;
if ((fraf = fopen(rafname,"rb")) == NULL)
return 0; // failure
if ((ftxt = fopen(txtname,"wt")) == NULL) { // changed mode
fclose(fraf);
return 0; // failure
}
fprintf(ftxt, "ID\tNAME\tBALANCE\n");
fprintf(ftxt, "---------------------------------------\n");
while(fread(&p, sizeof(p), 1, fraf) == 1) // use return value to loop
fprintf(ftxt, "%d\t%s\t%.2f\n", p.ID, p.name, p.balance);
fclose(ftxt);
fclose(fraf);
return 1; // success
}
int makefile(char* rafname)
{
FILE *fraf, *ftxt;
struct PERSON p = {1,"alpha", 123.45};
struct PERSON q = {2,"beta", 100.00};
struct PERSON r = {3,"gamma", 9.99};
if ((fraf = fopen(rafname,"wb")) == NULL)
return 0; // failure
fwrite(&p, sizeof(p), 1, fraf);
fwrite(&q, sizeof(q), 1, fraf);
fwrite(&r, sizeof(r), 1, fraf);
fclose(fraf);
return 1; // success
}
int main(void)
{
if (makefile("file.bin") == 0)
printf("Failure\n");
else {
if (CopyBin2Text("file.bin", "file.txt") == 0)
printf("Failure\n");
else
printf("Success\n");
}
return 0;
}
输出文本文件是
ID NAME BALANCE
---------------------------------------
1 alpha 123.45
2 beta 100.00
3 gamma 9.99