A filing program printing some unwanted ascii code
I made a program which stores a structure in a file but the output is different than as I expected,have a look,
/*
Students DataBase Program
Date:9th Dec,2010
Topic:Data base in C.
*/
#include <stdio.h>
int main()
{
struct student
{
char name[20];
int e_no;
}stud;
char temp[20],ch;
FILE *fp;
clrscr();
fp=fopen("D:\data1.txt","w+");
gotoxy(28,5);
printf("\nNED CIS ENROLMENT DATABASE\t");
do
{
gotoxy(28,10);
printf("\nEnter name of the student:\t");
gets(stud.name);
gotoxy(27,12);
printf("\nEnter your enrolment number:\t");
gets(temp);
atoi(temp,stud.e_no,10);
fwrite(&stud,sizeof(stud),1,fp);
printf("\nWant to enter another record?[y/n]");
ch=getche();
}
while(ch=='y'||ch=='Y');
getchar();
fclose(fp);
return 0;
}
The output should be the name and the enrolment number of the student but here's the kind of output开发者_如何学JAVA I get each time I enter any data.
OUTPUT ON FILE:
慦慨d@〃݅@赅㈃愀慨d@〃݅@赅㈃
Two things:
Don't use
gets
. It is prone to buffer overflows.If you want the data in the file to be in ascii form, you probably want to do something like
fprintf(fp, "%s:%d\n", stud.name, stud.e_no);
otherwise, it will print the binary representation of your data (not human readable, and unportable).
atoi
doesn't take three arguments. It takes one (the pointer to the string to convert) and returns an it. It's also deprecated - you should be using strtol instead. So your int stud_e isn't getting set.You are writing the in-memory/binary contents of stud to the file, so if you look at in a text editor or on the screen it is going to be unreadable (the name will probably look ok-ish, but the int (stud_e) will just print the characters that correspond to the binary data of the integer value
Gets has no bounds checking so you are reading as many characters as the user types. If they type more than 20 you will trample on other areas of memory and the program behaviour from then on is undefined and could do anything. You shouldn't use gets (use fgets or scanf with a limit instead)
Good practice would include checking the return values of fopen/fwrite/fclose for errors
精彩评论