繁体   English   中英

ifstream查找现有文件c ++

[英]ifstream to find existing files c++

我正在尝试从我为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)

编译,运行,按's'保存,'l'加载。 这一切都很好。

首次保存:

file.plot

节省第二次:

file.plot
file[1].plot

保存x次:

file.plot
file[1].plot

调试时,它表明file [1] .plot即使已存在也正在打开,因此我的循环正在退出。

注意:我不关心可移植性,因为工作代码是第一位的,但是我感谢任何格式化建议,因为我试图使我的代码尽可能地易于理解。 在此之前,我从未使用过_variable约定,请批评一下。

您处于循环状态的file以及您关闭的file均未引用循环内部声明的变量。
由于您在第一次迭代中关闭了“外部”文件,因此只需要迭代一次。

要重用相同的变量,请使用file.open(path, std::ios::binary | std::ios::in)
(将非const强制转换为const没有意义-除非您知道这既必要又正确,否则不要强制转换。)

而且i <= data.length将导致超出范围的数组访问,这是未定义的。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM