C/C++ 連續讀寫多個檔案
阿新 • • 發佈:2019-01-21
本文是為了解決多個檔案的讀寫問題:
問題:在我的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;
}