fwrite writes garbage value to file

2019-08-13 03:07发布

问题:

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



标签: c fwrite