c++ - 我正在尝试在某些条件下清除我的数据文件中的特殊字符,但不满足这些条件?

标签 c++ file-io

这是我的代码

此代码试图从 .txt 文件中删除特殊字符,如 ",',{,},(,) 并将其替换为空格。

#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#include <string.h>
#include <stdio.h>
#include <fcntl.h>
#include <iostream>
#include <time.h>
#include <fstream>

using namespace std;
int main(int argc, char *argv[])
{
    int fd;
    int i;
    int j;
    int len;
    int count = 0;
    int countcoma = 0;
    int countquote = 0;
    char buf[10];
    char spec[] = {',','"',':','{','}','(',')','\''};

    fd = open(argv[1],O_RDWR,0777);

    while (read(fd,buf,10) != 0) {
        len = strlen(buf);
        for (i=0;i<len;i++) {
            for (j=0;j<8;j++) {
                if (buf[i]==spec[j]) {
                    count =1;
                    countquote=0;
                    if (j==1) {
                        if (countcoma == 0) {
                            countcoma++;
                        }
                        if (countcoma == 1) {
                            countcoma--;
                        }
                    }
                    if ((j==7) && (countcoma ==1)) {        
                        countquote = 1;
                    }
                    break;
                }
            }
            //cout<<countquote;
            if ((count != 0) && (countquote == 0)) {
                buf[i] = ' ';
            }
            count = 0;      
        }
        lseek(fd, -sizeof(buf), SEEK_CUR);
        write(fd,buf,sizeof(buf));
        memset(buf,' ',10);
    }

    return 0;
}

现在我希望我的文件中双引号内的单引号保持不变,但所有特殊字符都被替换为代码中提到的空格。 我希望这些单引号保持不变 "what's"但在我运行文件后它变成 what s 而不是 what's

最佳答案

看看regex和其他图书馆。 (在 UNIX 上键入 man regex。)现在你不必再编写代码了,有无数的库可以为你做这件事。

关于c++ - 我正在尝试在某些条件下清除我的数据文件中的特殊字符,但不满足这些条件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17582357/

相关文章:

c++ - 循环模板

c++ - 在 Qt 中显示对话框的密码

r - 当有很多列时,使用 readr::read_csv() 导入数据时覆盖列类型

c - 不使用 fgets 打印文件中的行数

.net - 使用 .Net 计算目录中的文件数

c++ - 枚举比较运算符的重新定义

c++ - 这个语法 (0 < x < 10) 在 C++ 中有什么作用?

c++ - 如何在 C++ 中将字符串打印到控制台

file-io - Emacs - 当文件被外部修改时通知

c - 文件输入输出错误