FWRITE写入垃圾值到文件 [英] fwrite writes garbage value to file
问题描述
#include <stdio.h>
struct struct_type
{
int d;
};
int main()
{
struct struct_type *cust;
cust->d=13;
FILE* fp;
fp = fopen("path to file", "wb+");
or,
fp = fopen("path to file", "w+");
fwrite(cust, sizeof(struct struct_type), 1, fp);
fclose(fp);
return 0;
}
期望的输出
13
不过让写入文件的垃圾值。
However getting garbage value written to file.
推荐答案
假设你已经分配的内存为卡斯特
,或使用普通的结构,而不是一个指针,你' ð获取包含的二进制的再$ p $的INT 13的平台上psentation的文件。这将是不可读的,比方说,记事本。
Assuming you had allocated memory for cust
, or used a plain struct instead of a pointer, you'd get a file that contains the binary representation of the int 13 on your platform. Which would be unreadable in, say, notepad.
如果你看看一个十六进制编辑器输出中,你会看到几个零字节,一 0xOD
- 零字节数取决于整数的大小上您的平台,以及他们是否会之前或之后的13个字节取决于它的字节顺序。
If you look at the output in a hex editor, you'll see a few zero bytes and one 0xOD
- number of zero bytes depends on the size of ints on your platform, and whether they'll be before or after the 13 byte depends on its endianness.
如果你想与 13
A文件,如它的文字,使用 fprintf中
。
If you want a file with 13
as text in it, use fprintf
.
(因为我们还没有分配的内存,你的程序是未定义行为,可以做所有事情。)
(Since you haven't allocated memory, your program has undefined behavior, and can do anything at all.)
修复与堆栈结构:
#include <stdio.h>
struct struct_type
{
int d;
};
int main()
{
struct struct_type cust;
cust.d=13;
FILE* fp;
fp = fopen("path_to_file", "wb+");
fwrite(&cust, sizeof(cust), 1, fp);
fclose(fp);
return 0;
}
$ gcc -Wall -std=c99 -pedantic t.c
$ ./a.out
$ hexdump -C path_to_file
00000000 0d 00 00 00 |....|
00000004
要得到一个文本文件代替,替换 FWRITE
与
To get a text file instead, replace the fwrite
with:
fprintf(fp, "%d", cust.d); // or "%d\nd";
和从开放模式去掉B,因为这对二进制I / O。
and drop the "b" from the open mode since that's for binary I/O.
这篇关于FWRITE写入垃圾值到文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!