替换文本文件中的字符 - 逻辑错误?

时间:2012-04-20 11:32:41

标签: c argv

用户输入$。/ replace i xy data.txt
data.txt 包含“这是一个测试文件,仅限测试文件”。因此,所有我将被替换为xy,即thxys xys测试fxyle,仅测试fxyle

我觉得我很亲密。但是,我的代码不是用xy替换i,而是用x替换i。我认为错误是在第38行strcpy。 但是,从第30行到第40行的逻辑是否正确?我想说....

对于第一个缓冲区中的每个元素(buf)
    将buf元素复制到另一个缓冲区(temp)中,一次一个字符     如果buf元素=='我'           将'xy'复制到'i'

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


#define BUFFERSIZE 4096

/*replace i xy data.txt */

int main(int ac, char *av[])
{

    int in_fd, out_fd, n_chars, BufElement,j,x;
    ssize_t nread,nwrite;
    off_t newpos;
    char buf[BUFFERSIZE],temp[300];


        /*Open file containing original data*/
        if ( (in_fd=open(av[3], O_RDWR)) == -1 )
        {
            printf("Cannot open %s\n", av[3]);
            exit(1);
        }


        /*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++)
                {
                    temp[BufElement] = buf[BufElement];
                    if (buf[BufElement] == av[1][j])
                        strncpy(temp+BufElement,av[2],strlen(av[2])); /*ERROR*/

                }

            }
        }

        printf("%s\n",buf);
        printf("%s\n",temp);

            newpos = lseek(in_fd, 0, SEEK_SET); 

            nwrite = write(in_fd,temp,36); 

            close(in_fd);
        }

}

2 个答案:

答案 0 :(得分:3)

你只有一个BufElement的增量,但由于你的dest-buffer可能比输入更大或更小,你应该有两个计数器/指针;一个用于写入dest-buffer的下一个位置,另一个类似于输入缓冲区。

编辑:伪代码:

while src[i]
  if match
    dest[j] = replacement
    j += strlen(replacement)
    i += 1
  else
    dest[j] = src[i];
    i += 1
    j += 1

答案 1 :(得分:1)

您的i已替换为xy,但y被第buf(buf)中的temp[BufElement] = buf[BufElement]替换为strncpy(temp+BufElement,av[2],strlen(av[2]))

就像Peter Miehle所说,每次更换时都需要一个计数器来标记班次:

{{1}}
相关问题