如何使用C ++自动打开文件夹中的第一个文件? [英] How can I automatically open the first file in a folder using C++?

查看:392
本文介绍了如何使用C ++自动打开文件夹中的第一个文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

How can I automatically open and read the content of a file within a given directory from a C++ application without knowing the file's name?

例如的程序):

#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;
}

这将打印该目录中第一个文件的名称。我的问题是如何读取该特定文件的内容,并将其保存在.txt文档中。可以 ifstream 这样做吗?

This will print the name of the first file in that directory. My problem is how to read that particular file's content and save it in a .txt document. Can ifstream do that? (Sorry for my bad English.)

推荐答案

这样做

#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;
}

这篇关于如何使用C ++自动打开文件夹中的第一个文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆