linux ubuntu下使用io.h下的获取文件路径报错解决方法
1、报错描述
(1)代码
#include <io.h>
#include <iostream>
#include <fstream>
#include <string>
#include <vector>
using namespace std;
void getAllFiles(string path, vector<string>&files, string fileType)
{
//文件句柄
long hFile = 0;
struct _finddata_t fileInfo;
string p;
if ((hFile = _findfirst(p.assign(path).append("\\*" + fileType).c_str(), &fileInfo)) != -1){
do{
files.push_back(p.assign(path).append("\\").append(fileInfo.name));
} while (_findnext(hFile, &fileInfo) == 0);
_findclose(hFile);//关闭句柄
}
}
int main(int argc)
{
cout<<"308"<<endl;
vector<string> temp;
getAllFiles("\\mnt\\data2\\xuqiong\\image\\meiqi\\trunk\\testbd\\path", temp, ".jpg");
for (int i = 0; i < temp.size(); i++){
cout << temp[i] << endl;
}
return 0;
}
(2)报错内容:
/mnt/data2/xuqiong/image/meiqi/trunk/testbd/test_image.cpp: In function ‘void getAllFiles(std::__cxx11::string, std::vector<std::__cxx11::basic_string<char> >&, std::__cxx11::string)’:
/mnt/data2/xuqiong/image/meiqi/trunk/testbd/test_image.cpp:82:24: error: aggregate ‘getAllFiles(std::__cxx11::string, std::vector<std::__cxx11::basic_string<char> >&, std::__cxx11::string)::_finddata_t fileInfo’ has incomplete type and cannot be defined
struct _finddata_t fileInfo;
/mnt/data2/xuqiong/image/meiqi/trunk/testbd/test_image.cpp:85:87: error: ‘_findfirst’ was not declared in this scope
if ((hFile = _findfirst(p.assign(path).append("\\*" + fileType).c_str(), &fileInfo)) != -1){
/mnt/data2/xuqiong/image/meiqi/trunk/testbd/test_image.cpp:88:44: error: ‘_findnext’ was not declared in this scope
} while (_findnext(hFile, &fileInfo) == 0);
/mnt/data2/xuqiong/image/meiqi/trunk/testbd/test_image.cpp:90:25: error: ‘_findclose’ was not declared in this scope
_findclose(hFile);//关闭句柄
(3)分析
io.h 头文件可能不兼容跨平台操作。在windows下这个头文件运行稳定,但是在linux下这个头文件不能正常运行。
参考:https://www.cnblogs.com/gdut-gordon/p/9678175.html
2、解决方法
//头文件
#include <iostream>
#include <sys/types.h>
#include <dirent.h>
#include <vector>
#include <string.h>
using namespace std;
void GetFileNames(string path,vector<string>& filenames)
{
DIR *pDir;
struct dirent* ptr;
if(!(pDir = opendir(path.c_str())))
return;
while((ptr = readdir(pDir))!=0) {
if (strcmp(ptr->d_name, ".") != 0 && strcmp(ptr->d_name, "..") != 0)
filenames.push_back(path + "/" + ptr->d_name);
}
closedir(pDir);
}
int main() {
vector<string> file_name;
string path = "/home/image";
GetFileNames(path, file_name);
for(int i = 0; i <file_name.size(); i++)
{
cout<<file_name[i]<<endl;
}
return 0;
}
参考:https://blog.csdn.net/lsq2902101015/article/details/51373911
更多推荐
所有评论(0)