Reputation: 1
I am trying to write these parameters in a file .txt, but when I open the file (even before that it shows me a warining about the encoding) it appers like a bug, full of ????, like this:
$�U�z�G��?xpto%�U\���(\�?xpto&�Uףp=
��?xpto'�UR���Q�?xpto(�U�������?xpto)�UH�z�G�?xpto*�U��(\���?xpto+�U>
ףp=�?xpto,�U���Q��?xpto-�U433333�?xpto
I've searched a lot about but as it is a specifically error, i cannot find nothing about it. What is happening?
#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
typedef struct
{
int age;
double height;
char name[64];
} Person;
void printPersonInfo(Person *p)
{
printf("Person: %s, %d, %f\n", p->name, p->age, p->height);
}
int main (int argc, char *argv[])
{
FILE *fp = NULL;
int i;
Person p = {35, 1.65, "xpto"};
/* Validate number of arguments */
if(argc != 2)
{
printf("USAGE: %s fileName\n", argv[0]);
return EXIT_FAILURE;
}
/* Open the file provided as argument */
errno = 0;
fp = fopen(argv[1], "w");
if(fp == NULL)
{
perror ("Error opening file!");
return EXIT_FAILURE;
}
/* Write 10 itens on a file */
for(i = 0 ; i < 10 ; i++)
{
p.age = p.age+1;
p.height = p.height+0.03;
fwrite(&p, sizeof(Person), 1, fp);
}
fclose(fp);
return EXIT_SUCCESS;
}
Upvotes: 0
Views: 46
Reputation: 224457
The fwrite
function is writing the binary representation of the struct p
to the file. If you want to write text, use fprintf
:
fprintf(fp, "%d %f %s\n", p.age, p.height, p.name);
Upvotes: 2