How can i edit specific part of line in a text file in C?

1.1k views Asked by At

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.

2

There are 2 answers

1
BLUEPIXY On BEST ANSWER
#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;
}
3
The Gaming Hideout On

Probably try to make some sort of javascript script. I never tried making scripts outside of website / HTML/CSS related, but here's my idea.

Make a file named edit.js Open it [with] notepad, notepad++, or some sort of coding editor preferably. Notepad works, but Notepad++ I recommend ; its free. In reality, JavaScript isn't allowed to write, modify, or edit any file, only read them; This is due to security [and probably legal] reasons. So this is what I'd recommend:

Step One: Upload your text file and a new javascript file to a online hosting, or if I can think this out correctly, just make it on your harddrive in a folder. Convert the text file into a .html format, which can be done by:

Save As > File Type: All File Types > File name: mytextdocument.html

And also creating a .js file with it, by doing the same thing with notepad. The html file should include something on the lines of this.

<html>
  <head>
    <title>My Text Document</title>
    <script src="myscript.js"></script>
  </head>
  <body id="body" onLoad="replaceItem(); saveTextAsFile();">
    <div id="content">
      <ul>
        <li id="1" value="sword">Item="1" Name="Sword" Damage="2.5"</li>
        <li id="2" value="axe">Item="2" Name="Axe" Damage="3"</li>
      </ul>
    </div>
  </body>
</html>

The .js file should be on the lines of this;

function replaceItem()  {
  var x = document.getElementById("2");
  x.innerHTML = "Item='2' Name='Axe' Damage='3.5'";

}
  function saveTextAsFile()
{
    var textToWrite = document.getElementById("content").innerHTML;
    var textFileAsBlob = new Blob([textToWrite], {type:'text/plain'});
    var fileNameToSaveAs = "items.txt";

    var downloadLink = document.createElement("a");
    downloadLink.download = fileNameToSaveAs;
    downloadLink.innerHTML = "Download File";
    if (window.webkitURL != null)
    {
        // Chrome allows the link to be clicked
        // without actually adding it to the DOM.
        downloadLink.href = window.webkitURL.createObjectURL(textFileAsBlob);
    }
    else
    {
        // Firefox requires the link to be added to the DOM
        // before it can be clicked.
        downloadLink.href = window.URL.createObjectURL(textFileAsBlob);
        downloadLink.onclick = destroyClickedElement;
        downloadLink.style.display = "none";
        document.body.appendChild(downloadLink);
    }

    downloadLink.click();
}

NOTE

that before opening that HTML file, to make sure that you edit the content from the JavaScript file to what you want.