[英]Writing with FILE pointer, reading with ifstream
我必须处理代码,其中一方面使用FILE*
将信息写入文件,另一方面使用ifstream
读取信息。
我试图编译一个伪代码,该伪代码显示与原始代码相同的行为:
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <fstream>
#include <iostream>
int main()
{
FILE* outFile = fopen("testFile", "w");
char* posBuf = NULL;
unsigned int counter = 0;
posBuf = (char*) malloc( sizeof(int) + 2*sizeof(double) );
int iDummy = 123;
memcpy(posBuf+counter, (const void*) &iDummy, sizeof(int));
counter += sizeof(int);
double dDummy = 456.78;
memcpy(posBuf+counter, (const void*) &dDummy, sizeof(double));
counter += sizeof(double);
dDummy = 111.222;
memcpy(posBuf+counter, (const void*) &dDummy, sizeof(double));
fputs(posBuf, outFile);
fclose(outFile);
/////////////////////
std::ifstream myfile;
myfile.open("testFile", std::ios::in|std::ios::binary);
myfile.seekg (0, std::ios::end);
unsigned int length = myfile.tellg();
myfile.seekg (0, std::ios::beg);
char* posBuf2 = (char*) malloc( length );
myfile.read(posBuf2, length);
counter = 0;
int idummy = 0;
memcpy((void*) &idummy, posBuf2+counter, sizeof(int));
counter += sizeof(int);
printf("read integer: %u\n", idummy);
double ddummy = 1.0;
memcpy((void*) &ddummy, posBuf2+counter, sizeof(double));
counter += sizeof(double);
printf("read double: %f\n", ddummy);
ddummy = 1.0;
memcpy((void*) &ddummy, posBuf2+counter, sizeof(double));
counter += sizeof(double);
printf("read double: %f\n", ddummy);
myfile.close();
/////////////////////
FILE* inFile = fopen("testFile", "r");
char* posBuf3 = NULL;
unsigned int c = 0;
while ( ! feof (inFile) )
{
posBuf3 = (char*) realloc((void*) posBuf3, c+4);
fgets(posBuf3+c, 4, inFile);
c += 4;
}
idummy = 0;
memcpy((void*) &idummy, posBuf, sizeof(int));
printf("read again integer: %u\n", idummy);
ddummy =1.0;
memcpy((void*) &ddummy, posBuf+sizeof(int), sizeof(double));
printf("read again double: %f\n", ddummy);
ddummy =1.0;
memcpy((void*) &ddummy, posBuf+sizeof(int)+sizeof(double), sizeof(double));
printf("read again double: %f\n", ddummy);
return 0;
}
我从中得到的输出是:
read integer: 123
read double: 0.000000
read double: 0.000000
read again integer: 123
read again double: 456.780000
read again double: 111.222000
如您所见,反序列化仅在我也使用FILE*
读取FILE*
时才起作用。
问题 :对这种行为有解释吗?
谢谢!
更新时间 :
1)使用std::ios::in|std::ios::binary
打开ifstream
2)修复malloc
发布的代码存在一些问题:
posBuf
分配的内存范围(将1 int
和2 double
s复制到内存,但仅分配了sizeof(int) + sizeof(double)
),这是未定义的行为。 fputs()
将其参数视为以null终止的字符串,因此遇到空字符时将停止写入。 以二进制模式打开文件,并使用fwrite()
代替,后者不会将其输入视为以null终止的字符串。 该代码还有其他几个问题。
可避免的显式动态内存管理(不要介意malloc()
和realloc()
)。 只需替换为:
char posBuf[sizeof(int) + 2 * sizeof(double)];
while (!feof(inFile))
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.