通过迭代打开文件

时间:2012-07-05 10:22:29

标签: c++ c text-files

我的程序中有大约50个文件需要打开才能读取,我将所有这些文件从1.txt重命名为50.txt,希望我可以通过循环增加文件编号来传递文件名,但我不知道不知道如何/不认为可以将整数传递给char或者是否有更好的方法来解决我的情况。

char* filename = "";

for(int i =0; i < 50; i++)
{
if(i == 0){filename = "0.txt";}
if(i == 1){filename = "1.txt";} // ..
int num = 0, theinteger = 0;
ifstream in(filename, ios::binary);
unsigned char c;
while( in.read((char *)&c, 1) )
{       
        in >> theinteger;
        sca.chac[num]=theinteger; 
        num++;
}
}

return 0;

3 个答案:

答案 0 :(得分:5)

有一种相对简单的方法 - 在C中,使用sprintf函数,如下所示:

char filename[100];
sprintf(filename, "%d.txt", i);

在C ++中,使用ostringstream

ostringstream oss;
oss << i << ".txt";

答案 1 :(得分:3)

只需使用以下某项之一构建表示您必须打开的文件名称的字符串:

stringstream ss;
ss << anIntVal;
mystring = ss.str() + ".txt";

mystring = boost::lexical_cast<string>(anIntVal);
mystring += ".txt"

答案 2 :(得分:0)

查看sprintf功能。它的工作原理与printf函数类似,但它打印到char*。您必须确保char*足够大(您需要的字符数加上NULL终结符的1)。 然后,您可以在for循环中递增文件编号,并使用sprintf函数更新char* filename,然后打开文件。

在你的情况下:

char* filename[10];
int i;
for( i = 0; i <= 50; ++i){
    sprintf(filename,"%i.txt",i);
    //do stuff with the files
}

我发现它很有用(例如,为了使用填充的文件名进行良好的排序,这也使得为char*分配空间更加容易:

char* filename = "50.txt"; //the highest number should fit
int i;
for( i = 0; i <= 50; ++i){
    sprintf(filename,"%02i.txt",i);
    //do stuff with the files
}

希望这能帮到你!