如何使用C++自动打开文件夹中的第一个文件?

FCX*_*FCX 6 c++ file-io file

如何在不知道文件名的情况下从C++应用程序自动打开和读取给定目录中文件的内容?

例如(程序的粗略描述):

#include iomanip      
#include dirent.h     
#include fstream   
#include iostream   
#include stdlib.h

using namespace std;

int main()              
{
      DIR* dir;                                                   
      struct dirent* entry;                                          
      dir=opendir("C:\\Users\\Toshiba\\Desktop\\links\\");        
      printf("Directory contents: ");                             

      for(int i=0; i<3; i++)                                      
      {

           entry=readdir(dir);                                     
           printf("%s\n",entry->d_name);                           
      }
      return 0;
}
Run Code Online (Sandbox Code Playgroud)

这将打印该目录中第一个文件的名称.我的问题是如何读取该特定文件的内容并将其保存在.txt文档中.能ifstream做到吗?(对不起,我的英语不好.)

ayu*_*ush 5

这应该做到这一点

#include <iostream>
#include <boost/filesystem/operations.hpp>
#include <boost/filesystem/fstream.hpp>
using namespace boost::filesystem;
using namespace std;

void show_files( const path & directory, bool recurse_into_subdirs = true )
{
  if( exists( directory ) )
  {
    directory_iterator end ;
    for( directory_iterator iter(directory) ; iter != end ; ++iter )
      if ( is_directory( *iter ) )
    {
      cout << iter->native_directory_string() << " (directory)\n" ;
      if( recurse_into_subdirs ) show_files(*iter) ;
    }
    else
      cout << iter->native_file_string() << " (file)\n" ;
    copyfiles(iter->native_file_string());
  }
}

void copyfiles(string s)
{
  ifstream inFile;

  inFile.open(s);

  if (!inFile.is_open()) 
  {
    cout << "Unable to open file";
    exit(1); // terminate with error
  }
    //Display contents
  string line = "";

    //Getline to loop through all lines in file
  while(getline(inFile,line))
  {
    cout<<line<<endl; // line buffers for every line
        //here add your code to store this content in any file you want.
  }

  inFile.close();
}
int main()
{
  show_files( "/usr/share/doc/bind9" ) ;
  return 0;
}
Run Code Online (Sandbox Code Playgroud)