ifstream查找现有文件c ++

时间:2016-01-17 07:43:37

标签: c++ visual-studio-2010 windows-xp

我试图从我为OpenGL编写的代码块中保存一些实时图形数据,这些代码目前正在与Arduino进行通信。到目前为止,我在从Win10 VS15移植到WinXP VS10时遇到了很多问题,但是这些都是我所处的环境。

我希望我的程序尝试打开现有文件并检查它是否已打开。

如果文件是打开的,我想修改路径(附加递增的数字)并重新测试,直到文件没有打开。

如果/当文件没有打开时,我会使用该路径将我的数据输出到新文件。

int graph::save(const char *_path, int _format){
int i;
char *path;
double *_data;

char ext[9];

int _state = !state; //state is a class variable

if (_format == 0){
    sprintf(ext, "plot");
}
else if (_format == 1){
    sprintf(ext, "plotx");
}
else {
    printf("Invalid save format\n");
    return(1);
}

_data = new double[data.length];

//swap data stream buffer with static buffer if initially active
if (_state){pause();}

//copy data to new buffer to allow OpenGL loop access to data buffer
for (register int i = 0; i <= data.length; i++){
    _data[i] = data.data[i];
}

if (_state){pause();} //return to initial state if initially active

path = new char[strlen(_path) + 6 + 7]; //resize for extension

sprintf(path, "%s.%s", _path, ext); //append file extension

//open file
std::ifstream file((const char *)path, std::ios::binary | std::ios::in);

i = 1;
while(file.is_open()){ //while file is open(able)
    file.close(); //close opened file
    sprintf(path, "%s[%i].%s", _path, i, ext); //append incrementing number
    //open new file
    std::ifstream file((const char *)path, std::ios::binary | std::ios::in);
    i++;
}

file.close(); //close file

//open ofstream with un-openable file path
//store data etc etc (this all works)

编译,运行,按下&#39;保存,&#39; l&#39;载入。一切正常。

第一次保存:

file.plot

第二次保存:

file.plot
file[1].plot

保存x次:

file.plot
file[1].plot

调试时显示文件[1] .plot正在打开,即使它已经存在,所以我的循环正在退出。

注意: 我现在不关心可移植性,因为工作代码是第一位的,但是我确实感谢任何格式化建议,因为我尽量保持我的代码可以理解。我之前从未使用过_variable惯例,批判性的。

1 个答案:

答案 0 :(得分:0)

循环条件中的file以及您关闭的file.open(path, std::ios::binary | std::ios::in)不会引用循环内声明的变量。
因为你关闭&#34;外面&#34;在第一次迭代时,你只会迭代一次。

要重复使用相同的变量,请使用i <= data.length (除非你知道它既是必要的也是正确的,否则将非常规转换为常量并没有任何意义。)

并且SELECT resource,status,sum(status_count) as status_company_count from( SELECT dept1.actions.resource, dept1.action.status, Count(*) AS status_count FROM dept1.action GROUP BY dept1.action.status, dept1.action.resource UNION SELECT dept2.actions.resource, dept2.action.status, Count(*) AS status_count FROM dept2.action GROUP BY dept2.action.status, dept2.action.resource UNION SELECT dept3.actions.resource, dept3.action.status, Count(*) AS status_count FROM dept3.action GROUP BY dept3.action.status, dept3.action.resource .....) group by resource,status; 将导致超出范围的数组访问,这是未定义的。