我之前从未使用过 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 回答
你应该使用
int main()
而不是void main()
.您应该错误地检查对
opendir()
的调用 .您需要打开文件而不是使用
cin
来读取文件的内容 . 当然,你需要确保它被适当地关闭(这可能是通过什么都不做,让析构函数做它的东西) .请注意,文件名将是目录名(
"documents"
)和readdir()
返回的文件名的组合 .另请注意,您应该检查目录(或者,至少,对于
"."
和".."
,当前目录和父目录) .Andrew Koenig和Barbara Moo撰写的这本书有一章讨论如何在C语言中包含
opendir()
函数族,使它们对C程序表现得更好 .希瑟问道:
此刻的代码目前从标准输入读取,也就是
cin
. 这意味着如果您使用./a.out < program.cpp
启动程序,它将读取您的program.cpp
文件,无论它在目录中找到什么 . 因此,您需要根据您使用readdir()
找到的文件创建新的输入文件流:由于第一次读取操作(通过
getline()
)将失败(您可能应该安排根据其名称跳过.
和..
目录条目),您可能只需打开目录即可 . 如果fin
是循环中的局部变量,那么当外循环循环时,fin
将被销毁,这将关闭文件 .