- #include <stdio.h>
- #include <getopt.h>
- static int x[10],y[10],z[10];
- char filename[]="my-3d.txt";//a file name
- int errnum,title;//error number and title switch
- int input3d()//input 3d number into a file
- {
- FILE *fp;
- fp=fopen(filename,"a");
- if(fp==NULL){
- return errnum=1;
- }
- char date[9];
- int x,y,z;
- scanf("%s %1d %1d %1d",date,&x,&y,&z);
- fprintf(fp,"%8s\\t%d %d %d\\n",date,x,y,z);
- fclose(fp);
- return errnum=0;
- }
- void tongji3d()//open file and write times into array x,y,z
- {
- FILE *fp;
- fp=fopen(filename,"r");
- if(fp==NULL){
- errnum=5;
- return;
- }
- char a,b,c;
- char temp[9];
- while(fscanf(fp,"%8s\\t%c %c %c\\n",temp,&a,&b,&c)!=EOF){
- ++x[a-'0'];
- ++y[b-'0'];
- ++z[c-'0'];
- }
- fclose(fp);
- }
- void display(int cur[])//display 3d number times
- {
- if(title!=0){
- printf(" 0 1 2 3 4 5 6 7 8 9\\n");
- }
- if(cur==x){
- putchar('x');
- }else if(cur==y){
- putchar('y');
- }else{
- putchar('z');
- }
- putchar(':');
- for(int i=0;i<10;i++){
- printf("%d ",cur[i]);
- }
- putchar('\\n');
- }
- void disAll()//open and output file content
- {
- FILE *fp;
- fp=fopen(filename,"r");
- if(fp==NULL){
- errnum=5;
- return;
- }
- char a,b,c,temp[9];
- while(fscanf(fp,"%8s\\t%c %c %c\\n",temp,&a,&b,&c)!=EOF){
- printf("%8s\\t%c %c %c\\n",temp,a,b,c);
- }
- fclose(fp);
- }
- void usage()
- {
- printf(
- "usage:%s [options]\\n\\
- input with no arguments\\n\\
- -h display this help\\n\\
- -c clear empty\\n\\
- -x,y,z,t display times\\n"
- ,"my-3d");
- }
- int main(int argc,char *argv[])
- {
- int oc;
- while((oc=getopt(argc,argv,"ctxyzah"))!=-1){
- switch (oc){
- case 'c':
- remove(filename);
- return 0;
- case 't':
- if(title==0){
- printf(" 0 1 2 3 4 5 6 7 8 9\\n");
- }
- tongji3d();
- display(x);
- display(y);
- display(z);
- return 0;
- case 'x':
- title=1;
- tongji3d();
- display(x);
- return 0;
- case 'y':
- title=1;
- tongji3d();
- display(y);
- return 0;
- case 'z':
- title=1;
- tongji3d();
- display(z);
- return 0;
- case 'a':
- disAll();
- return 0;
- case 'h':
- usage();
- return 0;
- }
- }
- input3d();
- return errnum;
- }
- //该片段来自于http://www.codesnippet.cn/detail/180220148731.html
来源: http://www.codesnippet.cn/detail/180220148731.html