主題: c的程式...
瀏覽單個文章
starskgb
Regular Member
 

加入日期: Dec 2002
您的住址: 台北
文章: 98
c的程式...

#include<stdio.h>
#include<string.h>
#include<ctype.h>

int xwin();
void insert();
void inarray();
void save();

FILE *cptr;

struct book {
char name[30];
char age[4];
char phone[15];
char email[30];
};
struct book file[100];

char choice, *data, *buf={ "" };
int count=0;

int main( int argc, char *argv[] )

{
if( argc != 2 )
printf( "輸入格式不正確!!!\n" );
else {
if( ( cptr=fopen( argv[1], "r+" ) ) == NULL ) {
cptr=fopen(argv[1],"w");
fclose(cptr);
cptr=fopen(argv[1],"r+");
}
data=argv[1];
inarray();
fclose(cptr);
xwin();
}
return 0;
}

int xwin()
{

printf("(i) insert\n(x) exit\nchoice:");
scanf("\n%c",&choice);
switch (choice)
{
case 'i':
insert();
break;
case 'x':
count--;
save();
break;
default:
printf("沒有這選項!!!\n");
break;
}

return 0;
}

void insert()
{
char c;
printf( "name: " );
scanf( "%s", file[count].name );
printf( "age(1-150): " );
scanf( "%s",file[count].age );
printf( "phone:" );
scanf( "%s", file[count].phone );
printf( "email: " );
scanf( "%s", file[count].email );

while( c != 'n'&&c != 'b'&&c != 'x' )
{
printf( "\n(n)input next (b)back to main (x)exit and save data\nchoice:" );
scanf( "%c", &c );
}
if(c=='n') {
count++;
insert();
}
else
{
if(c=='b')
{
count++;
xwin();
}
else
save();
}

}

void inarray()
{

int x=0;

rewind(cptr);

while (!feof(cptr))
{
fgets( buf, 30, cptr );
sscanf( buf, "name:%s", file[x].name );
fgets( buf, 4, cptr );
sscanf( buf, "age:%s", file[x].age );
fgets( buf, 15, cptr );
sscanf( buf, "phone:%s", file[x].phone );
fgets( buf, 30,cptr );
sscanf( buf, "email:%s", file[x].email );
x++;
}
if(x==0)
count=0;
else
count=x-1;
}

void save() //將所有現有的資料寫入到檔案。
{
int counter=0;

cptr=fopen(data,"w");

while (counter<count)
{
fprintf( cptr, "name:%s\n", file[counter].name);
fprintf( cptr, "age:%s\n", file[counter].age);
fprintf( cptr, "phone:%s\n", file[counter].phone);
fprintf( cptr, "email:%s\n", file[counter].email);
counter++;
}
fclose(cptr);
}
     
      
__________________
=kgb=
舊 2003-10-02, 10:53 AM #1
回應時引用此文章
starskgb離線中