fwrite writes garbage value to file

▼魔方 西西 提交于 2019-12-24 13:46:59

问题


#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;

}

Expected output

13

However getting garbage value written to file.


回答1:


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.

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.

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.)


Fix with a struct on stack:

#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

To get a text file instead, replace the fwrite with:

fprintf(fp, "%d", cust.d); // or "%d\nd";

and drop the "b" from the open mode since that's for binary I/O.




回答2:


Allocate menory to your structure pointer cust

fwrite(cust, sizeof(struct struct_type), 1, fp);

Writes Binary data Into file.

The data which is present is binary data, that is Not garbage.

if you want to see whether it writes correctly or not read into object and print.

Use fread()

other wise convert integer to string and write into a text file.

Then you can able to see 13.



来源:https://stackoverflow.com/questions/19196083/fwrite-writes-garbage-value-to-file

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!