我正在尝试编写一个名为replace的linux命令,它将替换文件中的字符。我希望把它像这样:通过命令行替换字符
$./replace I XY test.txt
在这个例子中,test.txt
包含单词“这是一个测试文件”
我怎么能替换字符'I'
与"XY"
。我试图使用一个缓冲区,例如下面给出的代码,但由于缓冲区和argv声明不同,它会产生一个错误。此外,'I'
存储在一个数组元素中,而"XY"
需要两个。有没有解决这个问题的方法?
考虑text.txt
例如:
在这个例子中,第三个指标(其中包含'I'
)必须"XY"
更换这里是我的代码,它具有上述问题:
#define BUFFERSIZE 4096
/*replace i xy data.txt */
int main(int ac, char *av[])
{
int in_fd, out_fd, n_chars, BufElement,j;
char buf[BUFFERSIZE];
in_fd=open(av[3], O_RDWR);
/*Read characters from file to buffer*/
while ((nread = read(in_fd , buf, BUFFERSIZE)) > 0)
{
for (BufElement=0;BufElement < nread;BufElement++)
{
for (j=0; j < strlen(av[1]); j++)
{
if (buf[BufElement] == av[1][j])
buf[BufElement] = av[2]; /*ERROR*/
}/*for*/
}/*for*/
}/*while*/
}/*main*/
为什么不直接在这里发布代码? – slartibartfast 2012-04-20 06:23:00
可能重复的[如何替换c中的子字符串](http://stackoverflow.com/questions/3659694/how-to-replace-substring-in-c) – 2012-04-20 06:27:28