C语言实现一超市收银的例子“从文件读取商品编号及对应单价信息
typedef struct Ware_Tag
{
int index;
char name[20];
int price;
}DataType;
typedef struct Record_Tag
{
char date[30];
int index;
int num;
int total;
}Record;
#include
#include
#include
#include
void CreateStroage( char *fileName )
{
int num;
int i;
FILE *pF = NULL;
DataType *pDataType = NULL;
prin...全部
typedef struct Ware_Tag
{
int index;
char name[20];
int price;
}DataType;
typedef struct Record_Tag
{
char date[30];
int index;
int num;
int total;
}Record;
#include
#include
#include
#include
void CreateStroage( char *fileName )
{
int num;
int i;
FILE *pF = NULL;
DataType *pDataType = NULL;
printf( "请输入您要入库的商品数:\n" );
scanf( "%d", &num );
if ( num <= 0 )
{
return;
}
pDataType = ( DataType* ) malloc( sizeof( DataType ) * num );
if ( pDataType == NULL )
{
printf( "内存分配失败。
" );
return;
}
for( i=0; i index );
scanf( "%s", pDataType[i]。name );
scanf( "%d", &pDataType[i]。price );
}
pF = fopen( fileName, "a+" );
fwrite( pDataType, sizeof( DataType ), num, pF );
fclose( pF );
free ( pDataType );
}
void LoadData( char *fileName, DataType** pDataType, int num )
{
FILE *pF = NULL;
if ( num == 0 )
{
return ;
}
*pDataType = ( DataType* )malloc( sizeof( DataType ) * num );
if ( pDataType == NULL )
{
printf( "内存分配失败\n" );
return;
}
pF = fopen( fileName, "r" );
fread( *pDataType, sizeof( DataType ), num, pF );
fclose( pF );
}
int main( int argc, char *argv[] )
{
char *stroageFile = "storage。
dat";
char *recordFile = "Record。dat";
DataType *pDataType = NULL;
Record * pRecord = NULL;
int i;
int num = 3;
char *s = NULL;
time_t t;
FILE *pF = NULL;
CreateStroage( stroageFile ); //建立文件
LoadData( stroageFile, &pDataType, num );
printf( "取出的商品为:\n序号 名字 价格\n" );
for ( i=0; i index, pDataType[i]。name, pDataType[i]。price );
}
pRecord = ( Record* ) malloc ( sizeof( Record ) * num );
if ( pRecord == NULL )
{
printf( "内存分配失败,程序退出。
" );
return 0;
}
t = time( NULL );
s = ctime( &t );
printf( "请分别输入购买取出的三种商品的数量:\n" );
for( i=0; i num );
strcpy( pRecord[i]。date, s );
pRecord[i]。index = pDataType[i]。index;
pRecord[i]。
total = pRecord[i]。num * pDataType[i]。
price;
}
pF = fopen( recordFile, "a+" );
fwrite( pRecord, sizeof( Record ), num, pF );
free( pRecord );
free( pDataType );
return 1;
}
如果这个不行,可以自己修改一下就可以了。收起