读书人

急怎么实现将有相同格式的记录做个文件

发布时间: 2012-02-16 21:30:36 作者: rapoo

急,在线等,如何实现将有相同格式的记录做个文件分割?
请教弟兄们一个问题
一个有n条记录的文件,
比如说文件A.txt存储以下内容(每一位表示相应的信息,以*号表示未处理的信息位)
123a***
456b***
*789c**
**012**


如果想输出得到如下m个文件(即有相同格式的记录归入同一个文件)
1.txt
123a***
456b***

2.txt
*789c**

3.txt
**012**

怎么用C++实现,谢谢了。




[解决办法]

C/C++ code
//一个有n条记录的文件,//比如说文件A.txt存储以下内容(每一位表示相应的信息,以*号表示未处理的信息位)//123a***//456b***//*789c**//**012**//////如果想输出得到如下m个文件(即有相同格式的记录归入同一个文件)//1.txt//123a***//456b***////2.txt//*789c**////3.txt//**012**#include <stdio.h>FILE *fi,*fo[3];char c,n;char fn[40];char buf[40];int ln,i;int main() {    fi=fopen("A.txt","r");    if (NULL==fi) {        printf("Can not find file A.txt!\n");        return 1;    }    for (i=0;i<3;i++) {        sprintf(fn,"%d.txt",i+1);        fo[i]=fopen(fn,"w");        if (NULL==fo[i]) {            _fcloseall();            printf("Can not create file %s!\n",fn);        }    }    ln=0;    while (1) {        if (NULL==fgets(buf,40,fi)) break;        ln++;        if (4==sscanf(buf,"123a%c%c%c%c",&c,&c,&c,&n)) {            if ('\n'==n) fprintf(fo[0],"%s",buf);            else printf("File A.txt line %d format error, ignored!\n",ln);        } else        if (4==sscanf(buf,"456b%c%c%c%c",&c,&c,&c,&n)) {            if ('\n'==n) fprintf(fo[0],"%s",buf);            else printf("File A.txt line %d format error, ignored!\n",ln);        } else        if (4==sscanf(buf,"%c789c%c%c%c",&c,&c,&c,&n)) {            if ('\n'==n) fprintf(fo[1],"%s",buf);            else printf("File A.txt line %d format error, ignored!\n",ln);        } else        if (5==sscanf(buf,"%c%c012%c%c%c",&c,&c,&c,&c,&n)) {            if ('\n'==n) fprintf(fo[2],"%s",buf);            else printf("File A.txt line %d format error, ignored!\n",ln);        } else printf("File A.txt line %d format error, ignored!\n",ln);    }    _fcloseall();    return 0;}
[解决办法]
探讨

C/C++ code
//一个有n条记录的文件,
//比如说文件A.txt存储以下内容(每一位表示相应的信息,以*号表示未处理的信息位)
//123a***
//456b***
//*789c**
//**012**
//
//
//如果想输出得到如下m个文件(即有相同格式的记录归入同一个文件)
//1.txt
//123a***
//456b***
//
//2.txt
//*789c**
……

[解决办法]
将文件中所有记录读取到string数组中,遍历该数组,判断其所属模式,写入分类文件中。

读书人网 >C++

热点推荐