Reputation: 11
I am working on Linux in C and I am trying to write a structure to a file.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
struct stud{
char name[20];
char dept[20];
int id;
};
int main()
{
FILE *fptr;
int fwrt;
struct stud s;
printf("enter student name\n");
scanf("%s",s.name);
printf("enter student department\n");
scanf("%s",s.dept);
printf("enter student ID\n");
scanf("%d",&s.id);
fptr = fopen("tiger","wb");
if(fptr == NULL){
perror("error openning file :");
exit(EXIT_FAILURE);
}
fwrt = fwrite(&s,sizeof(struct stud),1,fptr);
if(fwrt == 0){
perror("error writing file :");
exit(EXIT_FAILURE);
}
// fprintf(fptr, "%d", s1->mark);
if(fclose(fptr) == EOF){
perror("error closing file :");
exit(EXIT_FAILURE);
}
}
Output: When I open the file to check I am getting:
Please let me know the way to solve this issue.
Upvotes: 0
Views: 170
Reputation: 321
You have to serialize your data, adding '\0' to the end of your char[].
But fwrite in binary mode is not convenient with dynamic structures, it's better when you can declare statically your structure's fields, so in your case it's good.
Instead of scanf, it's better if you use fgets like this :
#define MAX
if (fgets(s.name, MAX, stdin) == NULL)
{
//do what you want here
}
if (fgets(s.dept, MAX, stdin) == NULL)
{
//do what you want here
}
Upvotes: 0
Reputation: 437
Use
memset(&s, 0, sizeof(stud));
before writing to the strings to sterilize the data first, so that it will not show up when you try print it.
The reason id is complete garbage is because even though it is stored as text by scanf, you write to file as as binary. It should should also be a string.
also note that by having buffers this short, you are liable to get a buffer overflow if someone types a name or department that is longer than 20 characters.
Upvotes: 0
Reputation: 183858
Output: When I open the file to check I am getting:
- name I got but with additional characters
- dept I got but with additional characters
- id I got like some garbage value.
The fwrite
writes sizeof(struct stud)
bytes to the file, it doesn't care what these bytes contain. Since you haven't initialised s
, the name
and dept
arrays contain unspecified data and those bytes that weren't overwritten by the input (including the 0-terminator) retain their garbage values, those are written to the file too, hence the additional characters after name
and dept
. The id
is written to the file in its binary representation, when that is (tried to be) interpreted as text by the editor, that looks like garbage.
You should however guard against the input writing outside the array bounds, so you should limit the length of the string in the scanf
format, %19s
instead of %s
ensures that at most 19 characters are scanned into the 20-byte array, leaving place for the 0-terminator.
Upvotes: 1