Hello guys,
this is another of my homeworks, a very simple program.
the user have to select "mode1" or "mode2", and a file to use.
if he selects mode1, the program will ask an int number, then create a file and write randomly "adenina" or "citosina" or "guanina" or "timina" and stop.
if the user selects mode2, the program will read the file specified, count how many times there's wrote "adenina" "timina" "guanina" or "citosina" and printf the results.
now, there's no error (and no warnings!) when i compile it, and if i choose mode1 the program does everything he has to.
but if i choose mode2, it returns to me an error (like if i wrote something different) .. then i tried to force the program in mode 2, just to see if it works.. and surprise! the program won't do anything!
here you go with the code:
Code:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
int mode1(char*);
int mode2(char*);
int contarighe(char*);
void contastringhe(int,char*,int*);
int main(int argc, char** argv){
int choose;
if(argc!=3){
printf("Errore: inserire modalità e nome del file. \n");
exit(1);
}
if(strcmp(argv[1],"mode1")==0){
choose=mode1(argv[2]);
}else if(strcmp(argv[1],"mode2")==0){
choose=mode2(argv[2]);
}else printf("Comando non valido, specificare mode1 o mode2.\n");
if(choose==0 || choose==1){
printf("Il programma è stato eseguito correttamente.");
}
return 0;
}
int mode1(char* filename){
int n,i,temp;
FILE* file;
file=fopen(filename,"wb");
if(file==NULL){
printf("Il file non può essere creato, o non può essere aperto.\n");
exit(2);
}
printf("Inserire numero di stringhe.\n");
scanf("%d",&n);
srand(time(NULL));
for(i=0;i<n;i++){
temp=rand()%4;
switch(temp){
case 0:
fprintf(file,"ADENINA \n");
break;
case 1:
fprintf(file,"GUANINA \n");
break;
case 2:
fprintf(file,"TIMINA \n");
break;
case 3:
fprintf(file,"CITOSINA \n");
break;
default:
printf("Valore inaspettato.\n");
return -1;
}
}
fclose(file);
return 0;
}
int mode2(char* filename){
int n;
int cont[4];
FILE* file;
file=fopen(filename,"r");
if(file==NULL){
printf("Il file non può essere letto.\n");
exit(3);
}
n=contarighe(filename);
contastringhe(n,filename,&cont[0]);
printf("Nel file erano presenti: \n %d ADENINA \n %d GUANINA \n %d TIMINA \n %d CITOSINA \n", cont[0],cont[1],cont[2],cont[3]);
return 1;
}
int contarighe(char* filename){
char buffer[100];
int n;
FILE* file;
file=fopen(filename,"r");
while (fgets(buffer,100,file)!=NULL){
n++;
}
fclose(file);
return n;
}
void contastringhe(int n,char* filename,int* cont){
char nomi[4][8]= {"ADENINA", "GUANINA", "TIMINA", "CITOSINA"};
char temp [8];
int i,j;
FILE* file;
fopen(filename, "r");
for(i=0;i<n;i++){
fscanf(file,"%s",&temp);
for(j=0;j<4;j++){
if (strcmp(nomi[j],temp)==0){
cont[j]++;
}
}
}
fclose(file);
}