好久沒寫io操作了,手生了好多,為了防止自己老年痴呆,最簡單實用的c++代碼也push上來吧,
環境:mac,xcode(注意mac環境下Windows的函數不能用)
功能:打開一個文件目錄,把所有文件名讀取到一個TXT文件中
#include <iostream> #include <vector> #include <string> #include <dirent.h> #include <vector> #include <string> #include <fstream> #include <iostream> 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<string> 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<<files[i] <<endl; //message是程序中處理的數據 } else { cout<<"不能打開文件!"<<endl; } //cout << files[i] << endl; } outfile.close(); closedir(dir); return 0; }
評說:Windows底下操作更簡單,還可以篩選某一類的文件名,比如圖像等,見鏈接:http://blog.csdn.net/adong76/article/details/39432467
//獲取特定格式的文件名 void GetAllFormatFiles( string path, vector<string>& 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<string> files; char * distAll = "AllFiles.txt"; //讀取所有的文件,包括子文件的文件 //GetAllFiles(filePath, files); //讀取所有格式為jpg的文件 string format = ".jpg"; GetAllFormatFiles(filePath, files,format); ofstream ofn(distAll); int size = files.size(); ofn<<size<<endl; for (int i = 0;i<size;i++) { ofn<<files[i]<<endl; cout<< files[i] << endl; } ofn.close(); return 0; }
第二:打開文件,然后讀出特定的某幾行到新的文件中,用GetLine可以一行行讀取文件信息。
//生成兩個TXT文件分別存儲png圖像名和TXT圖像名 void genfilename(){ cout<<"begin"<<endl; 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<<"不能打開文件!"<<endl; } string line; int cont=1; //將文件中一行行的數據讀入line中 while(getline(allfile,line)){ if(cont&1) { pngfile<<line<<endl; cout<<line<<endl; }//奇數save png list else{ ptsfile<<line<<endl; } cont++; } ptsfile.close(); pngfile.close(); allfile.close(); }