Extract file name (not find file)

Source: Internet
Author: User

Once there is such a need, you want to achieve one. Although I know the Java built-in file operation library and C + + does not, but still do not want to change the language (disparage each other, the program Ape More light). So I went online to find a C version of the code, this is:

1#include <iostream>2#include <vector>3#include <string>4#include <cstring>5#include <io.h>6 using namespacestd;7 /**8 * Get all file names in a folder9 inputTen Path : Folder path One exd: File suffix, if blank, select all A Output - Files: Containers - */ the voidGetFileName (stringPathstringExd, vector<string>&files) - { -     ///file handle -     Longhfile =0; +     ///File Information -     struct_finddata_t FileInfo; +     stringPathName (path), Exdname ="\\*."+exd; A     if(hfile = _findfirst ((pathname+exdname). C_str (), &fileinfo)! =-1) at     { -          Do -{///If there is a folder, the iteration -             if(fileinfo.attrib&_a_subdir) -             { -                 if(strcmp (Fileinfo.name,".") && strcmp (Fileinfo.name,"..")) inGetFileName (pathname+"\\"+fileinfo.name, exd, files); -             } to             Else +             { -                 if(strcmp (Fileinfo.name,".") && strcmp (Fileinfo.name,"..")) the Files.push_back (fileinfo.name); *             } $} while(_findnext (hfile, &fileinfo) = =0);Panax Notoginseng         /** This code runs out of the fact that only one file can be found, and the reason for it is still troublesome -         */ the _findclose (hfile); +     } A } the intMain () + { -     stringPath"E:"); $vector<string>files; $GetFileName (Path,"", files); -      for(inti =0; I < files.size (); i++) -cout<<files[i]<<Endl; the     return 0; -}

The result has not been adjusted for a morning, really is the pit father.

Then I found that I could do it with DOS, and it was so simple that I wanted to go to the wall, like this.

@echo off
dir/s/b *.txt > file name. txt
Exit

In this line, dir does not have to say,/s means recursive traversal,/b represents a file line, *.txt means to find TXT file, and then write to a file.

Save it as bat and put it in the current folder. But it outputs an absolute path, and it has to be processed by itself.

The problem is solved, but it's too soon, I haven't felt it yet.

Later, I tried to use NB Python solution, in the process of implementation, I feel that I am engaged in translation. For example, I know to "get the current folder", and then which function in Python has this function? Find. I know "recursive traversal", but which function in Python has this function? Find. Most of the time is reading the document, learning grammar, modules, and there is no fun, perhaps because I am not familiar with the language. Finally, the recursive and non-recursive two versions are implemented as follows:

1 ImportOS2 ImportFnmatch3F=open ("picture. txt","w+")4  forFileinchOs.listdir (OS.GETCWD ()):5     ifFnmatch.fnmatch (file,'*.jpg'):6F.write (file+"\ n")7     #f.write (Os.path.realpath (file) + "\ n")8F.close ()
1 ImportOS2 ImportFnmatch3F=open ("picture. txt","w+")4  forTupinchOs.walk (OS.GETCWD ()):5LST = tup[2]6Dirpath =Tup[0]7      forFileinchLST:8         ifFnmatch.fnmatch (file,'*.jpg'):9F.write (Os.path.join (dirpath, file) +"\ n")Ten        #f.write (file+ "\ n") OneF.close ()

where GETCWD () is to get the current directory, Listdir () is to get the directory under all subdirectories (non-recursive), walk () is recursive get, return a list of Tuple,tuple contains three elements, respectively, is the current directory, the list of folders under the current directory, List of files in the current directory. Fnmatch () is a matching function; Realpath () returns the absolute path, join () connection path. Have to say, scripting language is still very convenient, the source code can be run as EXE directly.

Later, I met the lifting of the boom days, and finally can be implemented in C + +. The Boost FileSystem library implements file manipulation, and its readability is very good, with little need for interpretation.

1#include <iostream>2#include <fstream>3#include <string>4#include <boost/filesystem/operations.hpp>5 using namespacestd;6 using namespaceboost;7 namespaceFS =Boost::filesystem;8 usingRd_iter =Fs::recursive_directory_iterator;9 usingD_iter =fs::d irectory_iterator;Ten intMain () One { A     stringext; -cout<<"Please enter file format (with.)"<<Endl; -Cin>>ext; theOfstream Fout ("output.txt"); -Rd_iter POS ("./"), End; -      for(; pos! = End; + +)POS) -     { +         if(!is_directory (*pos) && -Pos->path (). Extension () = =ext) +{//file only A         //fout << pos->path (). FileName (). String () << Endl; at             //Absolute Path -         //fout << System_complete (Pos->path ()). String () << Endl; -             //relative Path -Fout << Pos->path (). Relative_path ().string() <<Endl; -         } -     } in}

Use "./" to indicate the current directory, how simple and intuitive. The D_iter is a non-recursive iterator, and the Rd_iter is a recursive iterator, where an iterator is used to traverse the path. Boost plays the magic of the iterator, and many usages look on their knees for the first time. More content can go to see Chrono's book, here does not say.

Extract file name (not find file)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.