提交C /添加数据

时间:2012-05-12 12:32:23

标签: c file-io

我正在尝试制作随机访问归档程序,它只是用于启动。我有关于提交addData函数的问题是不正常的,当我看起来biodata.txt有这么多奇怪的字符。我试图用结构文件。

  #include <stdio.h>
    #include <conio.h>

    struct biodata{
           int recno,age;
           char name[20],sex;
           float salary;
    }obj;


    int main(){
         void addData(void);

         void showRecord(void);
          char choice;

         while(1){



          printf("\n\n*****CHOOSE YOUR CHOICE*****\n");
          printf("1) ADD DATA\n");

          printf("2) SHOW RECORD\n");

          printf("Enter your choice : ");

          choice = getche();
          switch(choice){
             case '1' :   //call add data
                    addData();
                    break;

             case '2' :  //call show record
                    showRecord();
                    break;


          }
         }

    }


    //Adding Record to File
    void addData(){
         FILE *fp;

         fp = fopen("biodata.txt","a+t");

         printf("\n*****ADDING DATA*****\n");
         printf("\nEnter Record No : ");
         scanf("%d",&obj.recno);
         printf("Enter Name : ");

         scanf("%s",&obj.name);
         printf("Enter age : ");
         scanf("%d",&obj.age);

         printf("Enter Sex : ");
         scanf("%c",&obj.sex);
         printf("Enter Salary : ");
         scanf("%f",&obj.salary);
     fseek(fp,(obj.recno-1)*sizeof(obj),SEEK_SET);
    fwrite(&obj,sizeof(obj),1,fp);

         fclose(fp);
    }

    void showRecord(){
         FILE *fp;
         struct biodata obj;
         int rec;
         long pos;
         fp = fopen("biodata.txt","r");

         printf("\n*****SHOWING SPECIFIC RECORD*****\n");
         printf("\nEnter Record No : ");
         scanf("%d",&rec);
         pos = rec * sizeof(obj);
         fseek(fp,pos,SEEK_SET);
         if(feof(fp)==0)
        printf("\n\nNO DATA FOUND\n");
         else{
         fscanf(fp,"%d %s %d %c %f",&obj.recno,obj.name,&obj.age,&obj.sex,&obj.salary);
         printf("\n\n\tRecord No :  %d\n",obj.recno);
         printf("\tName : %s\n",obj.name);
         printf("\tAge  : %d\n",obj.age);
         printf("\tSex  : %c\n",obj.sex);
         printf("\tSalary : %f\n",obj.salary);
         }
         getch();
         fclose(fp);
    }

1 个答案:

答案 0 :(得分:1)

你在biodata.txt中获得奇怪字符的原因是你在函数fwrite()中使用addData()来做二进制流输出来输出你想要解释为文本的东西。您可能希望使用类似fprintf()的内容。

更具体一点,奇怪的字符很可能是您输出的结构的intfloat类型的成员 - 字符串"12345"和整数值12345没有相同的二进制表示,fscanf(fp, "%d %s %d %c %f", ...)期望前者(例如,整数12345表示为文本字符串"12345"),而{ {1}}直接输出二进制整数,不进行转换。因此,简而言之,您需要使用addData()之类的函数将整数和浮点数转换为适当的文本表示。