I'm a C learner and I'm having big difficulties with Files in C. Everytime I try to make a small program in C with Files, like printing a few datas on a simple txt it would ALWAYS print junk characters and/or ignore some of said datas. Even if I entirely copy a piece of presumably functioning code from stackoverflow.com or from Deitel textbook it just never works. Here's an example of code that I have been trying:
#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.dat", "w");
if (outfile == NULL)
{
fprintf(stderr, "\nError opend 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);
return 0;
}
This is a simple code that should write a few things on a dat. file. In this case, it won't print the numbers, just a small rectangle, and it prints the names without a newline. But I have seen worst, as many other codes will just print many junk characters. I'm using codeBlocks. Also, I have noticed that everything seems to work until I only use fprintf, fscanf and simple variables instead of structs. Anything else makes the code do weird stuff. Please help :(