std::ofstream,写入前检查文件是否存在

发布于 2024-10-04 20:10:05 字数 166 浏览 5 评论 0原文

我正在使用 C++ 在 Qt 应用程序中实现文件保存功能。

我正在寻找一种方法来检查所选文件在写入之前是否已存在,以便我可以向用户提示警告。

我正在使用 std::ofstream 并且我并不是在寻找 Boost 解决方案。

I am implementing file saving functionality within a Qt application using C++.

I am looking for a way to check to see if the selected file already exists before writing to it, so that I can prompt a warning to the user.

I am using an std::ofstream and I am not looking for a Boost solution.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(6

絕版丫頭 2024-10-11 20:10:05

文件存在功能

下面是我最喜欢的隐藏功能之一,我随身携带以供多种用途:

  #include <sys/stat.h>

  /**
    * File Exist Function
    *
    * @desc Check if a file exists
    *
    * @param filename - the name of the file to check
    *
    * @return 'true' if it exist, otherwise returns false.
    * */
    bool fileExists(const std::string& filename){
      struct stat buf;

      if (stat(filename.c_str(), &buf) != -1){ return true; }

      return false;
    }

我发现此解决方案比在您不打算打开文件时尝试打开文件更有品味流入或流出它。

File Exists Function

Below is one of my favorite tuck-away functions I keep on hand for multiple uses:

  #include <sys/stat.h>

  /**
    * File Exist Function
    *
    * @desc Check if a file exists
    *
    * @param filename - the name of the file to check
    *
    * @return 'true' if it exist, otherwise returns false.
    * */
    bool fileExists(const std::string& filename){
      struct stat buf;

      if (stat(filename.c_str(), &buf) != -1){ return true; }

      return false;
    }

I find this solution to be much more tasteful than trying to open a file when you don't intend to stream in or out of it.

杀手六號 2024-10-11 20:10:05

我建议 ifstream::good()

以下是使用 fstream 成员函数的示例:


  bool fileExists(const char *fileName)
  {
        ifstream inFile(fileName);
        return inFile.good();  
  }

该方法简短且可移植。当代码库很简单时,这是一个很好的解决方案(没有双关语)。

I suggest ifstream::good()

Here is an example of what using the fstream member function looks like:


  bool fileExists(const char *fileName)
  {
        ifstream inFile(fileName);
        return inFile.good();  
  }

The method is short and portable. When the code base is simple this is a good solution to use (no pun intended).

空袭的梦i 2024-10-11 20:10:05
fstream file;
file.open("my_file.txt", ios_base::out | ios_base::in);  // will not create file
if (file.is_open())
{
    cout << "Warning, file already exists, proceed?";
    if (no)
    { 
        file.close();
        // throw something
    }
}
else
{
    file.clear();
    file.open("my_file.txt", ios_base::out);  // will create if necessary
}

// do stuff with file

请注意,如果存在现有文件,这将以随机访问模式打开它。如果您愿意,可以关闭它并以追加模式或截断模式重新打开它。

fstream file;
file.open("my_file.txt", ios_base::out | ios_base::in);  // will not create file
if (file.is_open())
{
    cout << "Warning, file already exists, proceed?";
    if (no)
    { 
        file.close();
        // throw something
    }
}
else
{
    file.clear();
    file.open("my_file.txt", ios_base::out);  // will create if necessary
}

// do stuff with file

Note that in case of an existing file, this will open it in random-access mode. If you prefer, you can close it and reopen it in append mode or truncate mode.

叹倦 2024-10-11 20:10:05

使用 C 的 std::filesystem::exists ++17:

#include <filesystem> // C++17
#include <iostream>
namespace fs = std::filesystem;

int main()
{
    fs::path filePath("path/to/my/file.ext");
    std::error_code ec; // For using the noexcept overload.
    if (!fs::exists(filePath, ec) && !ec)
    {
        // Save to file, e.g. with std::ofstream file(filePath);
    }
    else
    {
        if (ec)
        {
            std::cerr << ec.message(); // Replace with your error handling.
        }
        else
        {
            std::cout << "File " << filePath << " does already exist.";
            // Handle overwrite case.
        }
    }
}

另请参阅 std::error_code

如果您想检查要写入的路径是否实际上是常规文件,请使用 <代码>std::filesystem::is_regular_file

With std::filesystem::exists of C++17:

#include <filesystem> // C++17
#include <iostream>
namespace fs = std::filesystem;

int main()
{
    fs::path filePath("path/to/my/file.ext");
    std::error_code ec; // For using the noexcept overload.
    if (!fs::exists(filePath, ec) && !ec)
    {
        // Save to file, e.g. with std::ofstream file(filePath);
    }
    else
    {
        if (ec)
        {
            std::cerr << ec.message(); // Replace with your error handling.
        }
        else
        {
            std::cout << "File " << filePath << " does already exist.";
            // Handle overwrite case.
        }
    }
}

See also std::error_code.

In case you want to check if the path you are writing to is actually a regular file, use std::filesystem::is_regular_file.

旧伤还要旧人安 2024-10-11 20:10:05

尝试 ::stat() (在 中声明)

Try ::stat() (declared in <sys/stat.h>)

╄→承喏 2024-10-11 20:10:05

其中一种方法是执行 stat() 并检查 errno
示例代码如下所示:

#include <sys/stat.h>
using namespace std;
// some lines of code...

int fileExist(const string &filePath) {
    struct stat statBuff;
    if (stat(filePath.c_str(), &statBuff) < 0) {
        if (errno == ENOENT) return -ENOENT;
    }
    else
        // do stuff with file
}

这与流无关。如果您仍然喜欢使用 ofstream 检查,只需使用 is_open() 检查。
示例:

ofstream fp.open("<path-to-file>", ofstream::out);
if (!fp.is_open()) 
    return false;
else 
    // do stuff with file

希望这会有所帮助。
谢谢!

One of the way would be to do stat() and check on errno.
A sample code would look look this:

#include <sys/stat.h>
using namespace std;
// some lines of code...

int fileExist(const string &filePath) {
    struct stat statBuff;
    if (stat(filePath.c_str(), &statBuff) < 0) {
        if (errno == ENOENT) return -ENOENT;
    }
    else
        // do stuff with file
}

This works irrespective of the stream. If you still prefer to check using ofstream just check using is_open().
Example:

ofstream fp.open("<path-to-file>", ofstream::out);
if (!fp.is_open()) 
    return false;
else 
    // do stuff with file

Hope this helps.
Thanks!

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文