c中的文件处理替换字符串

时间:2014-09-04 15:06:01

标签: c

我想用文件中的其他字符串覆盖字符串的某些部分。

我想在每行文件中覆盖。

我写了下面的代码,但这不起作用请帮忙。

假设文件有多行,其中一行包含:--- abcdefghioverwritefxyz89760

应转换如下: - abcdefghichangemadexyz89760

 char lineFileRecord [150];

 fp = fopen( "abc.txt","r+");

 while ( fgets (lineFileRecord , 150 , fp) != NULL )
 {
   char* sample;
   sample = strstr( lineFileRecord, "overwritef"); 

   //overwritef and changemade both have same size

   if( sample != NULL )
   {
      strncpy( sample, "changemade",10 ); // is the the correct way.

   }
 }

上面的代码没有替换内容。的文件。 如果我错了,请纠正我。

感谢您的回复。

2 个答案:

答案 0 :(得分:1)

您始终在特定位置读取/写入文件。要进行这些更改,您需要跳回,覆盖和跳回。

 char  lineFileRecord[150];
 FILE* fp = fopen("abc.txt","r+");
 long  posWrite = 0;
 long  posRead;

 while (fgets(lineFileRecord , 150 , fp) != NULL)
 {
    char* sample;
    sample = strstr(lineFileRecord, "overwritef"); 

    //overwritef and changemade both have same size

    if (sample != NULL)
    {
        // 1. Update your current lineFileRecord in memory.
        strncpy(sample, "changemade", 10);

        // 2. Remember where you were reading.
        posRead = ftell(fp);

        // 3. Jump back in the file to the beginning of your current lineFileRecord.
        //    This position was saved the previous time step 6 was executed.
        fseek(fp, posWrite, SEEK_SET);

        // 4. Now overwrite your file on disk! You were only changing the memory of
        //    of your program. And as you should know, memory and disk are
        //    different things. You need to overwrite the full lineFileRecord, 
        //    because ftell() does not give a clean byte position in text files.
        //    THANKS @chux!!!
        fwrite(lineFileRecord, 1, strlen(lineFileRecord), fp);

        // 5. Finally jump forward to where you are reading.
        fseek(fp, posRead, SEEK_SET);
    }

    // 6. Save the file position for the next overwrite.
    long posWrite = ftell(fp);
}

备注:在代码中停止使用TAB,它会弄乱缩进;总是使用空格!

答案 1 :(得分:0)

读取文件与将文件内容复制到内存*相同。您正在修改内容的副本,而不是原始副本。

您应该将整个文件的内容复制到内存中,更改该内容,然后覆盖整个文件,或者使用feekfputs等函数调用来修改文件的各个部分。此问题解释了如何写入文本文件:Write to .txt file?

*除非您使用的是内存映射文件。作为初学者,使用内存映射文件,使用它们并非易事。