2012-04-17 7 views
0

전에 dirent.h을 사용한 적이 없습니다. 텍스트 파일 (단수)을 읽는 데 istringstream을 사용했지만 디렉토리의 여러 텍스트 파일을 읽도록 프로그램을 수정해야했습니다. 이것은 dirent를 구현하려고 시도했지만 작동하지 않습니다.<dirent.h>을 처음 사용하여 디렉토리의 데이터에 액세스하려고 시도했습니다.

아마도 나는 stringstream과 함께 사용할 수 없습니까? 제발 조언.

가독성을 높이기 위해 내가하고있는 솜털 같은 것을 꺼 냈습니다. 이 은 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 = "-,.;:?\"'[email protected]#$%^&*[]{}|"; 
    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); 

    } 
+0

'void main()'은 C++의 주 프로그램에 대한 유효한 프로토 타입 중 하나가 아니기 때문에 (C에서는 비표준 임) 유의하십시오. –

+0

안녕하세요, 매우 유감입니다. 나는 upvoting에 대해 몰랐습니다! 돌아가서 이것을 치료했습니다. 머리를 가져 주셔서 감사합니다 :) –

답변

1

당신은 int main()하지 void main()를 사용한다.

opendir()으로 전화를 걸 때 오류가 확인되어야합니다.

파일 내용을 읽으려면 cin 대신 파일을 열어야합니다. 그리고 물론, 제대로 닫혀 있는지 확인해야합니다 (아무 것도하지 않고 소멸자가 그 물건을 처리하게하는 것일 수도 있습니다).

파일 이름은 디렉터리 이름 ("documents")과 readdir()에 의해 반환 된 파일 이름의 조합입니다.

디렉토리도 확인해야합니다 (또는 적어도 ".""..", 현재 디렉토리와 상위 디렉토리).

Andrew Koenig와 Barbara Moo의 저서 "Ruminations on C++"에는 opendir() 패밀리를 C++로 래핑하여 C++ 프로그램에서 더 잘 작동하도록하는 방법에 대해 설명하는 장이 있습니다.


헤더는 묻는다 : 나는 getline() 대신 cin에 넣어 무엇을

?

현재 코드는 표준 입력 (현재 cin)에서 읽습니다. 즉, ./a.out < program.cpp으로 프로그램을 시작하면 디렉토리에서 발견 된 내용과 상관없이 program.cpp 파일을 읽습니다.

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()를 통해) 첫 번째 읽기 작업 이후에 디렉토리를 여는 얻을 수 있습니다 실패합니다 : 그래서, 당신은 당신이 readdir()에서 발견 한 파일을 기반으로 새 입력 파일 스트림을 작성해야 (하지만 이름을 기준으로 ... 디렉토리 항목을 건너 뛸 수도 있습니다). fin이 루프의 로컬 변수 인 경우 외부 루프가 순환 할 때 fin이 파괴되어 파일을 닫아야합니다.

+0

그래, 내가 int로 바뀌 었어요 (왜 내가 처음에 이런 짓을했는지 모르겠다.) 또한 오류 검사를합니다. "documents"디렉토리가 정확합니다. 이전에 문서의 이름을 인쇄하는 것으로 작업 했었습니다. 그래서 나는 그것이 옳다고 생각합니다. 그래서 혼란 스럽습니다. cin 대신 getline()에 무엇을 넣어야합니까? 이것은 나를 매우 혼란스럽게합니다. –