C/C++ 连续读写多个文件

本文是为了解决多个文件的读写问题:
问题:在我的E盘下gene_info有300个.dat文件。那么我如何把这300个.dat文件中的内容读取出来呢?
这里写图片描述
每个.dat文件中的内容就是这样的字符串信息。我们不知道每个文件中有多少个字符串。我们可以知道的就是每个文件中有一些字符串信息,仅此而已。
这里写图片描述

代码:我们将300个.dat文件中的字符串读到rs中,并打印输出。至于写进多个文件,就是注释掉的部分,用fprintf()函数写入。

#include<stdio.h>
#include<stdlib.h>
#include<iostream>
#include<string.h>
#include<vector>
using namespace std;

vector<string> rs;


void read_write()
{
    FILE *fp = NULL;//输入 
    FILE *fq = NULL;//输出 
    char filename_body[10];
    for(int i = 1; i <= 300; i ++)
    {
        char filename[30] = "E://gene_info/gene_";
        memset(filename_body, 0, sizeof(filename_body));
        itoa(i, filename_body, 10);
        strcat(filename,filename_body);
        char filename_tail[5] = ".dat";
        strcat(filename,filename_tail);

        /*
        char outputfile[30] = "E://gene_info_res/";
        char outputfile_body[10];
        memset(outputfile_body, 0, sizeof(outputfile_body));
        itoa(i, outputfile_body, 10);
        strcat(outputfile, outputfile_body);
        char outputfile_tail[5] = ".txt";
        strcat(outputfile,outputfile_tail);
        */

        if((fp=fopen(filename, "r")) == NULL)
        {
            cout<<"open filename fail..."<<endl;
        }

/*      if((fq=fopen(outputfile, "w")) == NULL)
        {
            cout<<"open outputfile fail..."<<endl;
        }
*/      
        char str[20];
        while(fscanf(fp, "%s", str) == 1)
        {
            string tmp = str;
            rs.push_back(tmp);
        }
    //  fclose(fq);
        fclose(fp);
    }
}



int main()
{
    read_write();
    for(int i = 0; i < rs.size(); i ++)
        cout<<rs[i]<<endl;
    cout<<"DONE"<<endl;
    return 0;
}
  • 6
    点赞
  • 49
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值