首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >新加入<dirent.h>,尝试访问目录中的数据。

新加入<dirent.h>,尝试访问目录中的数据。
EN

Stack Overflow用户
提问于 2012-04-17 23:32:11
回答 1查看 2.3K关注 0票数 0

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

也许我不能把它和弦流一起用?请给我建议。

我已经拿出了我用可读性这个词做的毛茸茸的东西。它在一个文件中运行得很好,直到我添加了dirent.h文件。

代码语言:javascript
复制
#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);

    }
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2012-04-18 00:40:41

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

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

您需要打开一个文件,而不是使用cin读取文件的内容。当然,您还需要确保它是适当关闭的(这可能是不做任何操作,让析构函数执行它的操作)。

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

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

Andrew和Barbara的著作““C++上的反思””中有一章讨论了如何在C++中包装opendir()系列函数,使它们在C++程序中表现得更好。

希瑟问:

我应该在getline()而不是cin中放什么?

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

代码语言:javascript
复制
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将被销毁,这将关闭文件。

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/10200692

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档