首页 文章

<dirent.h>的新手,试图访问目录中的数据

提问于
浏览
0

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

也许我不能将它与stringstream一起使用?请指教 .

为了便于阅读,我做了've taken out the fluffy stuff that I' . 这对一个文件非常有效,直到我添加了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);

    }

1 回答

  • 1

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

    您应该错误地检查对 opendir() 的调用 .

    您需要打开文件而不是使用 cin 来读取文件的内容 . 当然,你需要确保它被适当地关闭(这可能是通过什么都不做,让析构函数做它的东西) .

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

    另请注意,您应该检查目录(或者,至少,对于 "."".." ,当前目录和父目录) .

    Andrew Koenig和Barbara Moo撰写的这本书有一章讨论如何在C语言中包含 opendir() 函数族,使它们对C程序表现得更好 .


    希瑟问道:

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

    此刻的代码目前从标准输入读取,也就是 cin . 这意味着如果您使用 ./a.out < 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 将被销毁,这将关闭文件 .

相关问题