假设我有一个 .txt 文件,其中包含以下两行:
Item="1" Name="Sword" Damage="2.5"
Item="2" Name="Axe" Damage="3"
如何用C将文本文件中斧头的伤害更改为3.5?
编辑:这就是我读取文本文件每一行的方式,我正在用文本信息填充 gtk 列表存储,dhd_LocalizaItem 它是一个获取“”内部内容的函数,例如Item =“1”,我将用该函数捕获 1,但是所有 gtk 都工作正常,正如我所说,我现在想要一个 C 函数/命令来编辑文本文件中一行的特定部分。
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);
}
对于我糟糕的英语大家表示歉意。
最佳答案
#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;
}
关于c - 如何在 C 中编辑文本文件中行的特定部分?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27069934/