【问题标题】:How can i edit specific part of line in a text file in C?如何在 C 中编辑文本文件中行的特定部分?
【发布时间】:2014-11-21 20:38:38
【问题描述】:

假设我有一个包含这两行的 .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); 
}

对不起,大家的英语不好。

【问题讨论】:

  • 查看fscanf函数
  • 对于每一行:读取它,根据需要进行调整,然后写入第二个文件。然后删除第一个文件并重命名第二个。发布您尝试过的内容。否则看起来 SO 正在做你的功课。
  • 但是如何调整呢?我已经知道如何阅读每一行了。抱歉,我还是编程新手。
  • 好吧,您需要在阅读后解析该行。将其分解成有意义的部分(如整数、浮点数和字符串)。正如@xjedam 提到的,scanf() 系列函数可以帮助您解决这个问题。一旦您在一组变量中获得了相关信息,通过调用printf() 系列重新组装更正后的行可能很容易。
  • @chux 我将发布阅读每一行的代码

标签: c file text edit file-manipulation


【解决方案1】:
#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;
}

【讨论】:

  • 好吧,由于 Gtk 和我的代码,我不得不做很多改变,但是你使用 fscanffprintf 的方式让我明白了。它现在正在工作!非常感谢!
【解决方案2】:

可能会尝试制作某种 javascript 脚本。我从未尝试过在网站/HTML/CSS 相关之外制作脚本,但这是我的想法。

创建一个名为 edit.js 的文件 最好用记事本、notepad++ 或某种编码编辑器打开它。记事本有效,但我推荐记事本++;免费。 实际上,JavaScript 不允许写入、修改或编辑任何文件,只能读取它们;这是出于安全 [可能是法律] 的原因。所以这是我的建议:

第一步:将您的文本文件和一个新的 javascript 文件上传到在线主机,或者如果我能正确地考虑这一点,只需将其放在硬盘上的文件夹中即可。 将文本文件转换为.html格式,可以通过:

另存为 > 文件类型:所有文件类型 > 文件名:mytextdocument.html

还可以用它创建一个.js 文件,用记事本做同样的事情。 html 文件应该在这行包含一些内容。

<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>

.js 文件应该在这行;

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();
}

注意

在打开该 HTML 文件之前,请确保将 JavaScript 文件中的内容编辑为您想要的内容。

【讨论】:

  • 这无法回答 OPs 的问题,因为他专门要求 C
  • 对不起@PhilippMurry,当他说我很困惑因为我从未听说过这个词时,因此假设他的意思是 C 盘 O.O
  • 您从未听说过 C 编程语言?
猜你喜欢
  • 2010-12-30
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-06-10
相关资源
最近更新 更多