文章目錄
- 1. 方法一:C語言之a(chǎn)ccess
- 2. 方法二:C++方法之ifstream
- 3. 方法三:fopen方法
- 4. 方法四:sys中的stat函數(shù)方法
1. 方法一:C語言之a(chǎn)ccess
可以使用C語言中unistd.h里的函數(shù)access()來判斷文件是否存在,其原型如下:
int access(const char *filename, int mode);
filename是文件名,mode有下列幾種方法:
mode | Description |
---|---|
F_OK | 測試文件是否存在 |
R_OK | 測試文件是否有讀權(quán)限 |
W_OK | 測試文件是否有寫權(quán)限 |
X_OK | 測試文件是否有執(zhí)行權(quán)限 |
返回0,表示存在,返回-1表示不存在。
- 使用方法
#include <unistd.h>
#include <stdio.h>
int main(void)
{
if (access("2.txt", F_OK) == 0)
{
printf("1.txt exists.\n");
}
else
{
printf("1.txt not exists.\n");
}
return 0;
}
2. 方法二:C++方法之ifstream
ifstream中的good方法可以判斷一個文件是否存在。
#include <iostream>
#include <string>
#include <fstream>
using namespace std;
bool isFileExists_ifstream(string& name) {
ifstream f(name.c_str());
return f.good();
}
int main()
{
string filename = "1.txt";
bool ret = isFileExists_ifstream(filename);
if (ret)
{
cout << "文件存在" << endl;
}
else
{
cout << "文件不存在" << endl;
}
}
3. 方法三:fopen方法
可以使用fopen的方式嘗試打開一個文件。文章來源:http://www.zghlxwxcb.cn/news/detail-637966.html
#include <iostream>
#include <stdio.h>
using namespace std;
bool isFileExists_fopen(string& name) {
if (FILE *file = fopen(name.c_str(), "r")) {
fclose(file);
return true;
} else {
return false;
}
}
int main()
{
string filename = "1.txt";
bool ret = isFileExists_fopen(filename);
if (ret)
{
cout << "文件存在" << endl;
}
else
{
cout << "文件不存在" << endl;
}
}
4. 方法四:sys中的stat函數(shù)方法
sys中的stat函數(shù)可以查閱文件的狀態(tài)。文章來源地址http://www.zghlxwxcb.cn/news/detail-637966.html
#include <iostream>
#include <sys/stat.h>
using namespace std;
bool isFileExists_stat(string& name) {
struct stat buffer;
return (stat(name.c_str(), &buffer) == 0);
}
int main()
{
string filename = "1.txt";
bool ret = isFileExists_stat(filename);
if (ret)
{
cout << "文件存在" << endl;
}
else
{
cout << "文件不存在" << endl;
}
}
到了這里,關(guān)于C++之判斷文件是否存在的幾種方法的文章就介紹完了。如果您還想了解更多內(nèi)容,請在右上角搜索TOY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!