替换文本文件中的单词,然后输出覆盖的版本

时间:2016-03-24 23:21:55

标签: c

对于这个问题,我要求首先从输入文本文件中读取,提示用户替换哪个单词/字符串,然后输出相同的文件(原始文件被覆盖)。问题是输入/输出文件名必须始终具有特定的名称,例如 test.txt (这是困扰我的)

这是我测试过的功能,它可以替换作业,但是现在我提示用户输入自己的“句子”,然后输入单词。我迷失了如何(总是)从 test.txt 读取,然后输出相同的替换字符串。

#include <stdio.h>
#include <string.h>
#include <stdlib.h>


char *w_replace(const char *s, const char *oldone, const char *newone)
{
char *ret;
int i, count = 0;
int newlen = strlen(newone);
int oldonelen = strlen(oldone);

for (i = 0; s[i] != '\0'; i++)
{
    if (strstr(&s[i], oldone) == &s[i])
    {
        count++;
        i += oldonelen - 1;
    }
}
ret = (char *)malloc(i + count * (newlen - oldonelen));
if (ret == NULL)
    exit(EXIT_FAILURE);
i = 0;
while (*s)
{
    if (strstr(s, oldone) == s) //compare 
    {
        strcpy(&ret[i], newone);
        i += newlen;
        s += oldonelen;
    }
    else
    ret[i++] = *s++;
}
ret[i] = '\0';
return ret;
}

int main(void)
{
char mystr[100], c[10], d[10];
char fileOld[32] = "test.txt";
char fileNew[32] = "test.txt";
char word_search[80];
char word_replace[80];
FILE *fp1, *fp2;

fp1 = fopen(fileOld,"r");
fp2 = fopen(fileNew,"w");

printf("Enter the word to replace :\n");
scanf(" %s",word_search);
printf("Enter the new word:\n");
scanf(" %s",word_replace);
char *newstr = NULL;

newstr = w_replace(fileOld, word_search , word_replace);


fputs(word_replace, fp2);
fclose(fp2);
fclose(fp1);
return 0;
}

因此,如果test.txt包含以下句子

This is a test

结果

Enter the word to replace :
This
Enter the new word:
That

新更新的test.txt文件只会是

That

而不是

That is a test

1 个答案:

答案 0 :(得分:0)

需要的值(使用上面给出的var名称):

#include <fcntl.h>

int file_descriptor;
int size_of_text = <whatever you want here>;
char *file_name = "test.txt";//or whatever
char newone[size_of_text];
char oldone[size_of_text];

从文件中读取:

file_descriptor = open(file_name,O_RDONLY);//O_RDONLY opens for read only
read(file_descriptor,oldone,sizeof(oldone));//reads file into oldone
close(file_descriptor);//closes so you don't accidentally read or write to it later, and so you can use it again

要写入文件:

file_descriptor = open(file_name,O_WRONLY | O_TRUNC);//O_WRONLY opens for writing only, O_TRUNC will truncate the file if it exists
write(file_descriptor,newone,sizeof(newone);//writes newone to file
close(file_descriptor);

有关read(),write(),open(),close():

的更多信息

http://www.gdsw.at/languages/c/programming-bbrown/c_075.htm