[英]Check whether file name already exists in a folder or not?
在C ++中,我需要检查输入的文件名是否存在于该文件夹中。 我正在使用g ++编译器为Linux编写代码。 请帮助大家:)
我在网上某个地方看到了这段代码来解决我的问题,但我强烈认为它无法达到我的目的:
ofstream fout(filename);
if(fout)
{
cout<<"File name already exists";
return 1;
}
您可以通过使用ifstream
进行测试来做到这一点,但是使用它和C级stat()
接口之间有细微的差别。
#include <cerrno>
#include <cstring>
#include <iostream>
#include <fstream>
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
using namespace std;
int main (int argc, const char *argv[]) {
if (argc < 2) {
cerr << "Filepath required.\n";
return 1;
}
ifstream fs(argv[1]);
if (fs.is_open()) {
fs.close();
cout << "ifstream says file exists.\n";
} else cout << "ifstream says file does not exist.\n";
struct stat info;
if ((stat(argv[1], &info)) == -1) {
if (errno == ENOENT) cout << "stat() says file does not exist.\n";
else cout << "stat() says " << strerror(errno) << endl;
} else cout << "stat() says file exists.\n";
return 0;
}
如果在已存在的文件上运行此文件, 并且对拥有读取权限 ,则两种方式都将得到相同的答案。
如果在不存在的文件上运行此命令,则两种方式都将得到相同的答案。
如果在一个存在的文件上运行它, 但没有读取权限 , 您将得到两个不同的答案 。 fstream
会说该文件不存在,但是stat()
会说它存在。 请注意,如果您在同一目录中运行ls
,即使您无法读取它,它也会显示该文件; 它确实存在。
因此,如果最后一种情况不重要-例如,您可能看不到的文件也可能不存在-请使用ifstream
测试。 但是,如果很重要,请使用stat()
测试。 有关更多信息,请参见man 2 stat
( 2
很重要),并记住,要使用它,您需要:
#include <cerrno>
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
如果stat()
失败(可能会发生stat()
,则需要cerrno
检查errno
。 例如,如果对路径中目录的读取权限被拒绝,则stat()
将失败,并且errno
等于EACCES
; 如果您在上述程序中尝试使用stat() says Permission denied
,则将显示stat() says Permission denied
。 这并不意味着文件存在。 这意味着您无法检查它是否存在。
请注意,如果您以前没有使用过errno
:在进行任何可能设置不同的呼叫之前,必须立即检查失败的呼叫。 但是,这是线程安全的。
如果您想跨平台使用C ++,我建议使用Boost Filesystem库 。
为了您的目的,我认为与此Boost示例代码相似
#include <iostream>
#include <boost/filesystem.hpp>
using namespace boost::filesystem;
int main(int argc, char* argv[])
{
path p (argv[1]); // p reads clearer than argv[1] in the following code
if (exists(p)) // does p actually exist?
{
if (is_regular_file(p)) // is p a regular file?
cout << p << " size is " << file_size(p) << '\n';
else if (is_directory(p)) // is p a directory?
cout << p << "is a directory\n";
else
cout << p << "exists, but is neither a regular file nor a directory\n";
}
else
cout << p << "does not exist\n";
return 0;
}
会做的工作。
也许您想要的是fstat: http ://codewiki.wikidot.com/c:system-calls:fstat
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.