2015-11-17 36 views
0

我已經寫了這個c程序來插入,查看,修改和刪除文件中的記錄。文件名是emp.dat。顯示,添加和刪除的代碼工作正常,但修改部分不起作用。該程序要求輸入細節進行修改,但沒有更新/修改。 守則:使用c程序在文件中修改記錄

#include<stdio.h> 
#include<stdlib.h> 
#include<string.h> 
#include<conio.h> 
void main() 
{ 
    FILE *outp,*inpt; 
    char another,choice; 
    struct emp 
    { 
     int emp_no,age; 
     char name[40]; 
     float bs; 
    }; 
    struct emp e; 
    char empname[40]; 
    long int recsize; 
    outp=fopen("emp.dat","r+"); 
    if(outp=='\0') 
    { 
     outp=fopen("emp.dat","w+"); 
     if(outp=='\0') 
     { 
      puts("cannot open file\n"); 
      exit(1); 
     } 
    } 
    recsize=sizeof(e); 
    while(1) 
    { 
     printf("1.Add records\n"); 
     printf("2.List records\n"); 
     printf("3.Modify records\n"); 
     printf("4.Delete records\n"); 
     printf("0. exit\n"); 
     printf("Your choice\n"); 
     fflush(stdin); 
     choice=getche(); 
     switch(choice) 
     { 
      case '1':       //code to add data 
      . 

      case '2':      //code to display data 

      case '3':      //code to modify data 
      another='Y'; 
      while(another=='Y') 
      { 
       printf("\nEnter name of employee to modify"); 
       scanf("%s",empname); 
       rewind(outp); 
       while(fread(&e,recsize,1,outp)==1) 
       { 
        if(strcmp(e.name,empname)==0) 
        { 
         printf("\nenter new name,age & gs"); 
         scanf("%d %s %d %f",&e.emp_no,&e.name,&e.age,&e.bs); 
         fseek(outp,-recsize,SEEK_CUR); 
         fwrite(&e,recsize,1,outp); 
         break; 
        } 
       } 
       printf("\nModify another record(Y/N)"); 
       fflush(stdin); 
       another=getche(); 
      } 
         printf("\n\n"); 
      break; 
      case '4':       //code to delete data 

      case '0': 
      fclose(outp); 
      printf("\n\n"); 
      exit(1); 
     } 
    } 
} 

enter image description here 如可以在輸出的名稱不會改變扎伊德牛到可以看到,也是如此年齡和GS

+0

你已經發布了很多代碼。如果您創建了最小,完整和可驗證的示例,您可以增加某人閱讀它並嘗試幫助您的可能性。在這裏閱讀更多:http://stackoverflow.com/help/mcve –

+0

這個'if(outp =='\ 0')'應該會拋出一個警告,即使是一個錯誤。只要做這個'if(!outp)' – milevyo

回答

2

你真的應該測試返回值。

提示請求name,age & gs,然後按照要求輸入它們。但指示scanf首先得到一個整數(emp_no)("%d %s %d %f")。錯過它立即失敗,沒有任何更新。

情況很容易檢測到:scanf返回成功轉換的次數。

相關問題