I am writing a structure to a file. Program compiled and executes successfully. In file, I get strange spaces and some character(not even on keyboard), including the structure.. Meanwhile when I read the file on console, I get correct output(the structures I tried to write in file).
Code:
// C program for writing
// struct to file
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
// a struct to read and write
struct person
{
int id;
char fname[20];
char lname[20];
};
int main ()
{
FILE *outfile;
// open file for writing
outfile = fopen ("person.txt", "w");
if (outfile == NULL)
{
printf(stderr, "\nError opening file\n");
exit (1);
}
struct person input1 = {1, "rohan", "sharma"};
struct person input2 = {2, "mahendra", "dhoni"};
// write struct to file
fwrite (&input1, sizeof(struct person), 1, outfile);
fwrite (&input2, sizeof(struct person), 1, outfile);
if(fwrite != 0)
printf("contents to file written successfully !\n");
else
printf("error writing file !\n");
// close file
fclose (outfile);
//To read from file
FILE * infile = fopen("person.txt");
struct person input;
if(infile==NULL)
{
printf("Error opening file!\n");
exit(1);
}
//read file contents till end of file
while (fread(&input,sizeof(struct person),1,infile)
printf("\nid = %d. name = %s %s\n",input.id,input.fname,input.lname);
fclose(infile);
return 0;
}
When I open file, I get these;
" rohan shama sc mahen dhoni"
(Without the quotes, where sc = strange character not even on my keyboard)
Please help, I'm a noob in this site.. thnks
P.S. this code was gotten from a website geeksforgeeks.com