I have a problem when passing a string to a file. I am almost sure that the problem comes from the way I read the variable, and so I leave the piece of code that I think is wrong. If you don't think the problem could come from there, I reassess the situation and send what I think is necessary.
I don't understand my problem because the system is actually saving something, but for example when I enter 5 teams, the system only registers 2 or 3 teams in the file. Does anyone know what this is about?
Here is the code:
My struct:
typedef struct String {
char string[50];
}string;
My variables:
int nEquipas = 0;
string equipa[50];
Here where I define the file location
#define FICHEIRO_EQUIPAS "Equipas.dat"
#define FICHEIRO_NEQUIPAS "nEquipas.dat"
Here when I ask the name of the n team:
void newTeam(string *equipa, int *nEquipas)
{
puts("INSIRA O NOME DA EQUIPA: ");
fflush(stdin);
gets(equipa[*nEquipas].string);
system("cls");
saveTeams(equipa, nEquipas);
saveNumTeams(nEquipas);
}
Here when I write the variable nEquipas:
void saveNumTeams(int *nEquipa)
{
// variaveis
FILE *ficheiro;
int i;
ficheiro = fopen(FICHEIRO_NEQUIPAS, "wb");
// se não foi possivel abrir o ficheiro (por exemplo: problema de permissões), mostra erro e sai
if (ficheiro == NULL)
{
printf("!!!não foi possivel abrir o ficheiro %s!!!\n", FICHEIRO_NEQUIPAS);
return;
}
//Escrever no ficheiro
fwrite(nEquipa, sizeof(int), 1, ficheiro);
// fechar o ficheiro
fclose(ficheiro);
}
Here I save the array string equipas
void saveTeams(string *equipa, int *nEquipa)
{
// variaveis
FILE *ficheiro;
int i;
ficheiro = fopen(FICHEIRO_EQUIPAS, "a+b");
// se não foi possivel abrir o ficheiro (por exemplo: problema de permissões), mostra erro e sai
if (ficheiro == NULL)
{
printf("!!!não foi possivel abrir o ficheiro %s!!!\n", FICHEIRO_EQUIPAS);
return;
}
//Procurar o fim
fseek(ficheiro, 0, SEEK_END);
//Escrever no ficheiro
fwrite(equipa, sizeof(string), *nEquipa, ficheiro);
// fechar o ficheiro
fclose(ficheiro);
}
And here I read the two variables:
void gerirFicheiros(string *equipa, int *nEquipas, membro medico[][50], int *nMedicos)
{
// variaveis
FILE *ficheiro;
int i;
// tentar abrir ficheiro (r = leitura b = binario)
ficheiro = fopen(FICHEIRO_NEQUIPAS, "rb");
// se não foi possivel abrir o ficheiro (por exemplo: por não existir), mostra erro e sai
if (ficheiro == NULL)
{
printf("!!!não foi possivel abrir o ficheiro %s!!!\n", FICHEIRO_NEQUIPAS);
return;
}
fread(nEquipas, sizeof(int), 1, ficheiro);
// fechar o ficheiro
fclose(ficheiro);
ficheiro = fopen(FICHEIRO_EQUIPAS, "rb");
// se não foi possivel abrir o ficheiro (por exemplo: por não existir), mostra erro e sai
if (ficheiro == NULL)
{
printf("!!!não foi possivel abrir o ficheiro %s!!!\n", FICHEIRO_EQUIPAS);
return;
}
// posicionar no inicio do ficheiro
rewind(ficheiro);
fread(equipa, sizeof(string), *nEquipas, ficheiro);
// fechar o ficheiro
fclose(ficheiro);
}
Am I reading correctly?
Thank you very much to everyone!