fstream 检查文件是否存在 c++
fstream Checking if file exists c++
大家好,我正在做一个RPG项目,我正在创建玩家文件,以便他们可以保存进度等。
我制作了一个测试程序,以便我可以以更简单的规模向您展示我正在寻找的内容
法典:
#include <iostream>
#include <fstream>
#include <string>
int main(){
std::string PlayerFileName;
std::cout << "Name Your Player File Name: ";
std::cin >> PlayerFileName;
std::ofstream outputFile;
std::string FileName = "Players/" + PlayerFileName;
outputFile.open(FileName); // This creates the file
// ...
}
我想检查并查看玩家目录中的玩家文件名是否已存在,以便人们无法保存他们的进度。
谢谢!
我建议以二进制模式打开文件并使用 seekg(( 和 tellg(( 来计算它的大小。如果大小大于 0 字节,则表示文件之前已打开并且其中写入了数据:
void checkFile()
{
long checkBytes;
myFile.open(fileName, ios::in | ios::out | ios::binary);
if (!myFile)
{
cout << "n Error opening file.";
exit(1);
}
myFile.seekg(0, ios::end); // put pointer at end of file
checkBytes = myFile.tellg(); // get file size in bytes, store it in variable "checkBytes";
if (checkBytes > 0) // if file size is bigger than 0 bytes
{
cout << "n File already exists and has data written in it;
myFile.close();
}
else
{
myFile.seekg(0. ios::beg); // put pointer back at beginning
// write your code here
}
}
像这样检查文件是否存在:
inline bool exists (const std::string& filename) {
struct stat buffer;
return (stat (filename.c_str(), &buffer) == 0);
}
- 使用这个需要记住
#include <sys/stat.h>
。
-
在 C++14 中可以使用以下内容:
#include <experimental/filesystem>
bool exist = std::experimental::filesystem::exists(filename);
C++17:(参考资料(
#include <filesystem>
bool exist = std::filesystem::exists(filename);
相关文章:
- C++模板来检查友元函数的存在
- 既然存在危险,为什么项目要使用-I include开关
- 我们可以访问一个不存在的联盟的成员吗
- C++:对不存在的命名空间使用命名空间指令
- C++quit()函数中可能存在作用域问题
- C++擦除(如果存在)
- g++ 说函数不存在,即使包含正确的标头
- 这个极客对极客的trie实现是否存在内存泄漏问题
- 有了gcc,是否可以链接库,但前提是它存在
- C++LinkedList问题.数据类型之间存在冲突?没有匹配的构造函数
- gcc和clang在表达式是否为常量求值的问题上存在分歧
- C++Builder中的OnClick事件签名存在问题
- 如何正确地将分支添加到已存在的树中
- 我知道函数调用中存在歧义.有没有办法调用foo()函数
- 如何检查QList中是否存在值
- 根据某个函数是否存在启用模板
- 如何将分支添加到已存在的TTree:ROOT
- 地图计数确实很重要,或者只是检查是否存在
- 通用C++/Python 多语言的存在
- 为什么我的共享库中存在展开符号