ifstream 查找现有文件 C++

ifstream to find existing files c++

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

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

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

If/when 文件打不开,然后我使用该路径将我的数据输出到一个新文件。

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 不引用循环内声明的变量。
由于您在第一次迭代时关闭了 "outside" 文件,因此您只会迭代一次。

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

i <= data.length会导致out-of-bounds次数组访问,这是未定义的。