开发者

A filing program printing some unwanted ascii code

开发者 https://www.devze.com 2023-01-30 06:06 出处:网络
I made a program which stores a structure in a file but the output is different than as I expected,have a look,

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:

  1. Don't use gets. It is prone to buffer overflows.

  2. 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).


  1. 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.

  2. 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

  3. 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)

  4. Good practice would include checking the return values of fopen/fwrite/fclose for errors

0

精彩评论

暂无评论...
验证码 换一张
取 消