文件内不替换值

时间:2014-08-02 03:32:44

标签: c

我正在创建一个读取shashank.txt文件的C程序,并将"!"的出现替换为文件中的"+"

输出应该只在同一个文件中

shashank.txt内容:

this is bsnl
!c practice
!

所需的输出(在同一文件中):

this is bsnl
+c practice 
+

我的节目:

#include <stdio.h>


#include<process.h>
int main ()
{
    // file pointer
    FILE *fp;
    int c;    

    // opening a file
    fp = fopen("shashank.txt", "r"); 

    //checking if correct file is opened or not
    if( fp == NULL ) 
    {
        printf("Error in opening file\n");
        return(-1);
    }

    while(!feof(fp)) 
    {
        //getting characterts
        c = getc(fp);

        /* replace ! with + */
        if( c == '!' ) 
        {
            // pushing + onto stream
             ungetc ('+', fp);                       
        }
        else 
        {
            //pushing c onto stream
            ungetc(c, fp); 
        }                     
    }

    return(0);
}

4 个答案:

答案 0 :(得分:2)

首先需要打开r+模式以读取现有文件中的写入。

fp = fopen("shashank.txt", "r+"); // Fix 1

尝试以下更改 -

    while((c = getc(fp))!=EOF) // Fix 2
    {

       /* replace ! with + */
       if( c == '!' )
       {
           fseek(fp,-1,SEEK_CUR); // It Moves current position indicator 1 position back
           fputc ('+', fp); // This will replace the ! with +
       }
   }

答案 1 :(得分:0)

这里有一些问题,你需要以“rw”模式打开文件,你的代码永远不会超出文件的第一个字符,因为它总是会推回一个字符。 尝试删除其他。

答案 2 :(得分:0)

“ungetc”将字符推回输入流。该流的下一个“getc”将返回被推回的字符。回送字符不会改变正在访问的文件; ungetc只影响流缓冲区,而不影响文件。 http://crasseux.com/books/ctutorial/ungetc.html

答案 3 :(得分:0)

你可以做一些解决方法。打开两个文件,一个是您正在阅读的文件,另一个是要写的文件。然后制作如下循环:

while (1) {
    c = fgetc(fp);
    if (c == EOF) {
        break;
    }
    if (c != '!') {
        fprintf(fp2,"%c",c);
    }
    else {
        fprintf(fp2,"+");
    }
}

所以,如果它不是!,请将读取文件中的字符写入您正在编写的文件中。如果是,请写+。然后,关闭文件,删除C程序中的旧文件,然后将新文件重命名为旧文件。

正如我所说,这是一个解决方法,@ Sathish表明是好的。只是另一种解决这个问题的方法。

相关问题