将Ascii代码文件转换为二进制文件

时间:2014-11-05 13:42:19

标签: c file-io

我有将ASCII代码文件转换为二进制文件的问题。代码能够读取文件并将数据作为ASII代码打印到其他文件中(使用fprintf);但是,当我尝试从ASII代码转换为二进制文件(使用fwrite),然后再次使用(fread)该文件。它没有产生正确的答案。我怀疑fwrite函数可能不起作用。你能告诉我如何解决这个问题吗?非常感谢你。

============================================
Code to convert from ASCII to binary file
===========================================
# include <stdio.h>
# include <stdlib.h>
# include <string.h>

typedef struct _FileData
{
int a;
double b;
char dataStr[56];
 }FileData;


int main()
{
// open read file   
FILE * infile=fopen("output.txt", "r");
if(infile==NULL)
{
    printf("Error opening file");
    exit(1);
}

// open write file
FILE * outfile = fopen("out_file.txt","wb");
if( outfile==NULL)
{
    printf("Error writting on file");
    exit(1);
}

FileData input; // pointer for read file
FileData output; // pointer for write file

while( fscanf(infile,"%d %lf %[^\n]s",&input.a,&input.b,&input.dataStr)==3)
{
    /*printf("%d\n",input.a);
    printf("%.3lf\n",input.b);
    printf("%s\n",input.dataStr);*/
    //fprintf(outfile,"%d\n %.3lf\n %s\n",input.a,input.b,input.dataStr);
    fwrite(&output,sizeof(FileData),1,outfile);


}
fclose(infile);
fclose(outfile);
return 0;
   }
==============================================================
Code to convert from binary file to ASCII code file
=============================================================
# include <stdio.h>
# include <stdlib.h>
# include <string.h>

typedef struct FileData
{
int a;
double b;
char dataStr[56];
}FileData;
int main()
{

FILE * infile=fopen("out_file.txt", "rb");
if(infile==NULL)
{
 printf("Error opening file");
 }
FileData input;
while(fread(&input,sizeof(struct FileData),sizeof(struct FileData),infile))
{
printf("%d\n",input.a);
printf("%.3f\n",input.b);
printf("%s\n",input.dataStr);
}

return 0;
}

===========================================================
Data 
==========================================================

47
34.278
This is a line of text

48
23.678
This a very very long line

2 个答案:

答案 0 :(得分:1)

fread(&input,sizeof(struct FileData),sizeof(struct FileData),infile)

应改为

fread(&input,sizeof(struct FileData),1,infile)

您想要编写1个大小为sizeof(struct FileData)的结构

同时检查mash5的答案,他建议在使用fwrite写作时编写变量input而不是output

答案 1 :(得分:0)

在您的ASCII转换代码中,输入文件被读入一个变量input

fscanf(infile,"%d %lf %[^\n]s",&input.a,&input.b,&input.dataStr)

但正在将另一个未初始化的变量output写入输出文件:

 fwrite(&output,sizeof(FileData),1,outfile);   

也许你应该写

 fwrite(&input,sizeof(input),1,outfile);   

代替?