c(API) 對文件內容的增刪查改

#include "stdio.h"
#include "stdlib.h"

int no,other;
char name[20];

//查詢
void find()
{
   FILE *fp;    
  fp=fopen("C:\\Users\\Administrator\\Desktop\\date.txt","r");  
if(fp==NULL)
exit(1); //異常處理
while(1)
{
  fscanf(fp,"%d %s %d",&no,name,&other);
if(fgetc(fp)==EOF)
 break; //遇文件結束符
printf("%03d %s %d\n",no,name,other);
}
fclose(fp);
}
//添加
void add()
{
    FILE *fp;
fp=fopen("C:\\Users\\Administrator\\Desktop\\date.txt","a+"); //追加
printf("Input NO,Name,Other:\n");


scanf("%d %s %d",&no,name,&other);


fprintf(fp,"%03d %s %d\n",no,name,other);

fclose(fp);
}
//修改
void edit()
{
     printf("請輸入修改的學號:\n");
         int e_temNo;
int e_no[20],e_other[20];
char e_name[20][20];


scanf("%d",&e_temNo);
         int l=0;
  FILE *fp;
      fp=fopen("C:\\Users\\Administrator\\Desktop\\date.txt","r");  
if(fp==NULL)
exit(1); //異常處理
while(1)
{
  fscanf(fp,"%d %s %d",&e_no[l],e_name[l],&e_other[l]);
  
if(fgetc(fp)==EOF)
 break; //遇文件結束符
  // printf("%03d %s %d\n",no,name,other); 
l++;
}
fclose(fp);
fp=fopen("C:\\Users\\Administrator\\Desktop\\date.txt","w");
for(int i=0;i<l;i++)
{
if(e_temNo==e_no[i])  //學號匹配    
{
printf("原信息爲:%03d %s %d\n",e_no[i],e_name[i],e_other[i]);
printf("Input NO,Name,Other:\n");
                        scanf("%d %s %d",&e_no[i],e_name[i],&e_other[i]);
}
   fprintf(fp,"%03d %s %d\n",e_no[i],e_name[i],e_other[i]); //原樣寫回
}
  fclose(fp);
}
//刪除
void del()
{
   printf("請輸入刪除的學號:\n");
         int e_temNo;
int e_no[20],e_other[20];
char e_name[20][20];


scanf("%d",&e_temNo);
         int l=0;
  FILE *fp;
      fp=fopen("C:\\Users\\Administrator\\Desktop\\date.txt","r");  
if(fp==NULL)
exit(1); //異常處理
while(1)
{
  fscanf(fp,"%d %s %d",&e_no[l],e_name[l],&e_other[l]);
  
if(fgetc(fp)==EOF)
 break; //遇文件結束符
  // printf("%03d %s %d\n",no,name,other); 
l++;
}
fclose(fp);
fp=fopen("C:\\Users\\Administrator\\Desktop\\date.txt","w");
for(int i=0;i<l;i++)
{
if(e_temNo!=e_no[i])  //學號匹配    
{
       fprintf(fp,"%03d %s %d\n",e_no[i],e_name[i],e_other[i]); //原樣寫回
}
}
  fclose(fp);
}


int main(int argc, char* argv[])
{
int v;
printf("1:查詢 2:插入 3:修改 4:刪除\n");
while(~scanf("%d",&v))
{
if(v==1)
{
  find();
}
else if(v==2)
{
           add();
}
else if(v==3)
{
 edit();
}
else
{
 del();
}
       printf("1:查詢 2:插入 3:修改 4:刪除\n");
}
return 0;
}

date.txt 文件內容:

001 小額 111
002 小何 222
003 小樣 333


參考文獻:

http://zhidao.baidu.com/question/1830196103434926340.html

http://blog.chinaunix.net/uid-11600035-id-2866020.html

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章