[英]How do I read back an 8 byte number after writing it to a file?
我能够将数字的8字节表示形式写入文件。 但是,当我回读它时,却得不到预期的电话号码。 在下面的代码中,我试图将数字5000
写入并读回testfile.txt
。
#include <stdio.h>
int main()
{
// Open file
FILE *fp;
if ((fp = fopen("testfile.txt","w+")) == NULL)
{
// Handle error
}
// Write 8 byte number to file
long long n = 5000;
fwrite(&n, 8, 1, fp);
// Seek to EOF and check that the file is 8 bytes
fseek(fp, 0, SEEK_END);
long locend = ftell(fp);
printf("Endbyte: %ld\n",locend);
// Seek back to start of file and print out location
fseek(fp, -8, SEEK_END);
long loc = ftell(fp);
printf("Location: %ld\n",loc);
// Read and print out number
long long *out;
fread(out, 8, 1, fp);
long long num = (long long) out;
printf("Number: %lld\n", num);
/* Cleanup */
close(fp);
return(0);
}
进行testfile.txt
会给我以下内容:
00000000 88 13 00 00 00 00 00 00 |........|
00000008
十六进制值13
和88
的二进制表示为5000
,这确认它已正确写入(我相信)。
不幸的是,我的程序输出不同意:
Endbyte: 8
Location: 0
Number: 140734934060848
如您所见,回读的数字与写入的数字不匹配。 我假设这是我读回它的方式有问题。
我很惊讶它甚至没有崩溃就运行! fread
本质上与fwrite
完全相同,只是在另一个方向上。 它需要一个指向内存块的指针,但是您要向其传递未初始化的指针。
long long *out; //This is a pointer that is pointing to an undefined area of memory.
fread(out, 8, 1, fp); //fread is now writing the number to that undefined area of memory
您要做的是创建一个long long
的普通旧fwrite
并像使用fwrite
一样传递对其的引用。
long long out; //This is a location in memory that will hold the value
fread(&out, 8, 1, fp); //fread is now writing the number to the area of memory defined by the 'out' variable
out是一个指针,需要先取消引用才能将其分配给num。
out
是一个指针,因此它必须指向有效地址,然后才能为其分配值,并且要获取其值,必须使用&
而不强制转换。
这是一个正确的代码:
long long num;
fread(&num, 8, 1, fp);
printf("Number: %lld\n", num);
还有一件事,请按照以下步骤更正您的close
功能
fclose(fp);
请注意, close
使用文件描述符和fclose
使用FILE *
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.