如何在 c++ 中访问同一文件夹中某些文件的内容

How to access to the content of some files in a same folder in c++?

本文关键字:文件 文件夹 c++ 访问      更新时间:2023-10-16

我有一个文件夹,这个文件夹有 5 个文本文件。

我想阅读这些文本文件。

我知道通过这段代码,我可以在一个文件夹中拥有子文件夹的列表:

#include <dirent.h> 
#include <stdio.h> 
int main(void)
{
  DIR           *d;
  struct dirent *dir;
  d = opendir("c://myproject/task1");
  if (d)
  {
   while ((dir = readdir(d)) != NULL)
   {
    printf("%sn", dir->d_name);
   }
   closedir(d);
  }
  return(0);
}

但是,我想读取这些文件(每个文件内容都是一个字符)并在屏幕上打印此字符。

所以我使用了这段代码:

int main(void)
{
  DIR           *d;
  struct dirent *dir;
  d = opendir("c://myproject/task1");
  if (d)
  {
   while ((dir = readdir(d)) != NULL)
   {
    if(strcmp(dir->d_name,".")==0 || strcmp(dir->d_name,"..")==0 )
    {continue;}
    ifstream myReadFile;
    myReadFile.open(dir->d_name);
    char output;
    if(myReadFile.is_open())
    {
     while (!myReadFile.eof())
     {
      myReadFile >> output;
      cout<<output<<endl;
     }
    }
   }
   closedir(d);
  }
  return(0);
}

但是,我没有得到输出。

你能帮我找到代码中的问题吗?

您必须在

dir->d_name之前连接folder_address,而不是使用 strcat myReadFile.open(dir->d_name);

因为dir->d_name只有文件名,在可执行文件的当前路径中找不到,因此无法打开。

执行以下操作:

#include<dirent.h>
#include<iostream>
#include<fstream>
#include<string.h>
using namespace std;
int main(void)
{
  DIR           *d;
  struct dirent *dir;
  char folder_address[100];
  strcpy(folder_address,"c://myproject/task1");
  d = opendir(folder_address);
  if (d)
  {
   while ((dir = readdir(d)) != NULL)
   {
    if(strcmp(dir->d_name,".")==0 || strcmp(dir->d_name,"..")==0 )
        {continue;}
    ifstream myReadFile;
    char fname[200];
    strcpy(fname, folder_address);
    strcat(fname, "/");
    strcat(fname, dir->d_name);
    myReadFile.open(fname);
    char output;
    if (myReadFile.is_open())
    {
     while (1)
     {
      myReadFile >> output;
      if(myReadFile.eof())
       break;
      cout<<output<<endl;
     }
    }
        myReadFile.close();
   }
   closedir(d);
  }
  return(0);
}

问题是您在保留路径处打开一个文件夹:

 d = opendir(folder_address);  // I suppose folder_address is a string

但是您读取的d_name包含文件名,而不是完整路径名。 因此,如果folder_address不是当前目录,则打开将失败。

在尝试打开文件之前,您必须构建完整的路径名。 尝试类似操作:

  string fullname(folder_address); 
  if (fullname.size()!=0) 
      fullname += "/";  // assuming it's posix
  fullname += dir->d_name;
  ifstream myReadFile(fullname);
  char output;
  if (myReadFile.is_open()) {  
      while (myReadFile>>output) {  // loop on read (NEVER ON EOF in C++)
          cout<<output<<endl;
      }
  }

重要说明:顺便说一下,您不应该循环 eOf,而是循环 C++ 流上的读取操作。