linux 显示文件名写到txt,C++获取某个路径下所有文件的文件名,读写TXT文件到新的文件...
好久沒寫io操作了,手生了好多,最簡單實用的C++代碼也push上來吧。
環境:mac,xcode(注意mac環境下Windows的函數不能用)
功能:打開一個文件目錄,把所有文件名讀取到一個TXT文件中
#include
#include
#include
#include
#include
#include
#include
#include
using namespace std;
int readfiledir()
{
struct dirent *ptr;
DIR *dir;
string PATH = "/Users/anitafang/Downloads/Datasets/300W/300w/01_Indoor";
dir=opendir(PATH.c_str());
vector files;
cout << "文件列表: "<< endl;
while((ptr=readdir(dir))!=NULL)
{
//跳過'.'和'..'兩個目錄
if(ptr->d_name[0] == '.')
continue;
//cout << ptr->d_name << endl;
files.push_back(ptr->d_name);
}
//寫入TXT文件
ofstream outfile;
outfile.open("/Users/anitafang/Downloads/Datasets/300W/300w/01_Indoor/list111.txt", ofstream::app);? //myfile.bat是存放數據的文件名
for (int i = 0; i < files.size(); ++i)
{
if(outfile.is_open())
{
outfile<
}
else
{
cout<
}
//cout << files[i] << endl;
}
outfile.close();
closedir(dir);
return 0;
}
評說:Windows底下操作更簡單,還可以篩選某一類的文件名,比如圖像等
//獲取特定格式的文件名
void GetAllFormatFiles( string path, vector& files,string format)
{
//文件句柄
long? hFile? =? 0;
//文件信息
struct _finddata_t fileinfo;
string p;
if((hFile = _findfirst(p.assign(path).append("\\*" + format).c_str(),&fileinfo)) !=? -1)
{
do
{
if((fileinfo.attrib &? _A_SUBDIR))
{
if(strcmp(fileinfo.name,".") != 0? &&? strcmp(fileinfo.name,"..") != 0)
{
//files.push_back(p.assign(path).append("\\").append(fileinfo.name) );
GetAllFormatFiles( p.assign(path).append("\\").append(fileinfo.name), files,format);
}
}
else
{
files.push_back(p.assign(path).append("\\").append(fileinfo.name) );
}
}while(_findnext(hFile, &fileinfo)? == 0);
_findclose(hFile);
}
}
int main()
{
string filePath = "testimages\\water";
vector files;
char * distAll = "AllFiles.txt";
//讀取所有的文件,包括子文件的文件
//GetAllFiles(filePath, files);
//讀取所有格式為jpg的文件
string format = ".jpg";
GetAllFormatFiles(filePath, files,format);
ofstream ofn(distAll);
int size = files.size();
ofn<
for (int i = 0;i
{
ofn<
cout<< files[i] << endl;
}
ofn.close();
return 0;
}
第二:打開文件,然后讀出特定的某幾行到新的文件中,用GetLine可以一行行讀取文件信息。
//生成兩個TXT文件分別存儲png圖像名和TXT圖像名
void genfilename(){
cout<
ofstream pngfile;
ofstream ptsfile;
ifstream allfile;
ptsfile.open("/Users/anitafang/Downloads/Datasets/300W/300w/01_Indoor/ptslist.txt", ofstream::app);? //
pngfile.open("/Users/anitafang/Downloads/Datasets/300W/300w/01_Indoor/pnglist.txt", ofstream::app);? //
allfile.open("/Users/anitafang/Downloads/Datasets/300W/300w/01_Indoor/list.txt");
if(!allfile.is_open()){
cout<
}
string? line;
int cont=1;
//將文件中一行行的數據讀入line中
while(getline(allfile,line)){
if(cont&1) {
pngfile<
cout<
}//奇數save png list
else{
ptsfile<
}
cont++;
}
ptsfile.close();
pngfile.close();
allfile.close();
}
總結
以上是生活随笔為你收集整理的linux 显示文件名写到txt,C++获取某个路径下所有文件的文件名,读写TXT文件到新的文件...的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: java 设计char类型_JAVA中的
- 下一篇: 多个 本地仓库_【运维工具】搭建npm私