Let's say that I have a .txt file which contains these two lines:
Item="1" Name="Sword" Damage="2.5"
Item="2" Name="Axe" Damage="3"
How can i change the damage of the Axe to 3.5 in the text file with C?
EDITED: this is how i read each line of the text file, and I'm filling a gtk list store with the text info, the dhd_LocalizaItem its a function to get what is inside the " " e.g. Item="1", i will catch the 1 with that function, but all gtk thing its working fine, as I said, i want now a C function/command to edit specific part of a line in a text file.
void get_message() {
GtkTreeIter dhd_iter;
FILE * dhd_pFile;
char dhd_G_CodProduto[256];
char dhd_G_NomeProduto[256];
char dhd_contaItem[16];
char dhd_quantidade[32];
char dhd_valorItem[32];
char dhd_getbuf[1024];
dhd_chekDel = 0;
dhd_pFile = fopen ("Logs/logCancelar.txt", "r");
if(dhd_pFile == NULL) {
printf("Erro! Nao foi possivel abrir o log de cancelamento!\n");
}
else {
while( (fgets(dhd_getbuf, sizeof(dhd_getbuf), dhd_pFile))!=NULL ) {
dhd_LocalizaItem (dhd_getbuf, dhd_stringItem);
dhd_restou = dhd_LocalizaItem( "Item=" , dhd_getbuf);
strcpy(dhd_contaItem,dhd_restou);
dhd_LocalizaItem (dhd_getbuf, dhd_strong);
dhd_restou = dhd_LocalizaItem( "CodProduto=" , dhd_getbuf);
strcpy(dhd_G_CodProduto,dhd_restou);
dhd_LocalizaItem (dhd_getbuf, dhd_strung);
dhd_restou = dhd_LocalizaItem( "NomeProduto=" , dhd_getbuf);
strcpy(dhd_G_NomeProduto,dhd_restou);
dhd_LocalizaItem (dhd_getbuf, dhd_streng);
dhd_restou = dhd_LocalizaItem( "Quantidade=" , dhd_getbuf);
strcpy(dhd_quantidade,dhd_restou);
dhd_LocalizaItem (dhd_getbuf, dhd_stringTotal);
dhd_restou = dhd_LocalizaItem( "ValorTotal=" , dhd_getbuf);
strcpy(dhd_valorItem,dhd_restou);
gtk_list_store_append(GTK_LIST_STORE( mainWindowObjects.liststore ), &dhd_iter);
gtk_list_store_set(GTK_LIST_STORE( mainWindowObjects.liststore ), &dhd_iter,
ITEM, dhd_contaItem,
CODIGO, dhd_G_CodProduto ,
DESCRICAO, dhd_G_NomeProduto ,
QTD, dhd_quantidade,
VALOR, dhd_valorItem,
-1 );
}
}
fclose(dhd_pFile);
}
And sorry for my bad english everyone.
#include <stdio.h>
#include <string.h>
typedef struct arms {
int id;
char name[32];
double damage;
} Arms;
int read_arms(Arms *a, FILE *fp){
return fscanf(fp, " Item=\"%d\" Name=\"%[^\"]\" Damage=\"%lf\"",
&a->id, a->name, &a->damage);
}
void write_arms(Arms *a, FILE *fp){
fprintf(fp, "Item=\"%d\" Name=\"%s\" Damage=\"%3.1f\"\n",
a->id, a->name, a->damage);
}
#define ARMSFILE "arms.dat"
void change_damage_by_name(const char *name, double damage){
FILE *fin, *fout;
Arms a;
fin = fopen(ARMSFILE, "r");
fout = fopen("arms.tmp", "w");
while(EOF!=read_arms(&a, fin)){
if(strcmp(a.name, name)==0)
a.damage = damage;
write_arms(&a, fout);
}
fclose(fin);
fclose(fout);
remove(ARMSFILE);
rename("arms.tmp", ARMSFILE);
}
int main(void){
change_damage_by_name("Axe", 3.5);
return 0;
}