【问题标题】:New to <dirent.h>, trying to access data in a directory<dirent.h> 的新手,尝试访问目录中的数据
【发布时间】:2023-03-04 19:10:01
【问题描述】:

我以前从未使用过dirent.h。我正在使用 istringstream 读取文本文件(单数),但需要尝试修改程序以读取目录中的多个文本文件。这是我尝试实现 dirent 的地方,但它不起作用。

也许我不能将它与字符串流一起使用?请指教。

为了便于阅读,我已经去掉了我用单词做的蓬松的东西。在我添加了 dirent.h 内容之前,这 对一个文件非常有效。

#include <cstdlib>
#include <iostream>
#include <string>
#include <sstream>  // for istringstream
#include <fstream>
#include <stdio.h>
#include <dirent.h>

void main(){

    string fileName;
    istringstream strLine;
    const string Punctuation = "-,.;:?\"'!@#$%^&*[]{}|";
    const char *commonWords[] = {"AND","IS","OR","ARE","THE","A","AN",""};
    string line, word;
    int currentLine = 0;
    int hashValue = 0;

    //// these variables were added to new code //////

    struct dirent *pent = NULL;
    DIR *pdir = NULL; // pointer to the directory
    pdir = opendir("documents");

    //////////////////////////////////////////////////


    while(pent = readdir(pdir)){

        // read in values line by line, then word by word
        while(getline(cin,line)){
            ++currentLine;

            strLine.clear();
            strLine.str(line);

            while(strLine >> word){

                        // insert the words into a table

            }

        } // end getline

        //print the words in the table

    closedir(pdir);

    }

【问题讨论】:

  • 请注意,void main() 不是 C++ 中主程序的有效原型之一(并且在 C 中是非标准的)。
  • 嗨,我很抱歉,我不知道投票!已经回去并解决了这个问题。谢谢你的提醒:)

标签: c++ directory opendir istringstream dirent.h


【解决方案1】:

您应该使用int main() 而不是void main()

您应该在检查对 opendir() 的调用时出错。

您需要打开一个文件而不是使用cin 来读取文件的内容。而且,当然,您需要确保它被适当地关闭(这可能是什么都不做,让析构函数来做它的事情)。

请注意,文件名将是目录名 ("documents") 和 readdir() 返回的文件名的组合。

还请注意,您可能应该检查目录(或至少检查".""..",当前目录和父目录)。

Andrew Koenig 和 Barbara Moo 所著的《"Ruminations on C++"》一书中有一章讨论了如何在 C++ 中封装 opendir() 系列函数,以使它们在 C++ 程序中表现得更好。


希瑟问:

我应该在getline() 中输入什么而不是cin

此时的代码从标准输入读取,即 cin。这意味着,如果您使用./a.out &lt; program.cpp 启动程序,它将读取您的program.cpp 文件,而不管它在目录中找到什么。因此,您需要根据使用readdir() 找到的文件创建一个新的输入文件流:

while (pent = readdir(pdir))
{
    ...create name from "documents" and pent->d_name
    ...check that name is not a directory
    ...open the file for reading (only) and check that it succeeded
    ...use a variable such as fin for the file stream
    // read in values line by line, then word by word
    while (getline(fin, line))
    {
         ...processing of lines as before...
    }
}

您可能只需打开目录即可,因为第一次读取操作(通过getline())将失败(但您可能应该根据名称安排跳过... 目录条目)。如果fin是循环中的局部变量,那么当外循环循环时,fin将被销毁,这应该关闭文件。

【讨论】:

  • 好的,所以我已将 void 更改为 int (不知道为什么我首先这样做了。)并且还进行了错误检查。目录“文档”是正确的,我之前只是打印出文档的名称。所以我认为它是正确的。所以..我很困惑,我应该在 getline() 中而不是 cin 中放入什么?这些让我非常困惑。
猜你喜欢
  • 2019-04-13
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-05-03
  • 1970-01-01
相关资源
最近更新 更多