2015-09-26 7 views
0

Я читаю файлы в каталоге и передаю его функции, я думаю, что делаю это неправильно, не в состоянии понять.чтение файлов в каталоге C++

Вот мой код, сначала он читает файлы в папке и отправляет их функции для дальнейших операций.

#include <dirent.h> 
#include <stdio.h> 
#include <vector> 
#include <string> 
#include <iostream> 
using namespace std; 
std::vector<std::string> fileName; 


int main(void) 
{ 

DIR   *d; 
struct dirent *dir; 
vector<string> fileList; 
int i=0; 
d = opendir("files"); 
if (d) 
{ 
while ((dir = readdir(d)) != NULL) 
{ 
i++; 
fileList.push_back(dir->d_name); 

} 
for(int i=0;i<fileList.size();i++) { 
    cout<<fileList[i]<<endl; 
    doSomething(fileList[i]); 
} 
closedir(d); 
    } 

return(0); 
} 

int doSomething(fileName) { 
//do something 
} 

Ошибка

main.cpp: In function ‘int main()’: 
main.cpp:29:28: error: ‘doSomething’ was not declared in this scope 
doSomething(fileList[i]); 
         ^
main.cpp: At global scope: 
main.cpp:37:26: error: cannot convert  ‘std::vector<std::basic_string<char> >’ to ‘int’ in initialization 
int doSomething(fileName) { 
        ^
main.cpp:37:28: error: expected ‘,’ or ‘;’ before ‘{’ token 
int doSomething(fileName) { 
         ^
+0

Если форматировать Ваш код более последовательно и с помощью отступов людей может быть более вероятно, чтобы попытаться выяснить, что вы сделали неправильно. – Galik

ответ

1

Поскольку ваша doSomething функция определена после того, как основной, не видно, что вызывает первую ошибку. Правильный путь должен был бы, по крайней мере объявить функцию первого:

int doSomething(); //declaration 

int main() 
{ 
    doSomething(); //now the function is declared 
} 

//definition 
int doSomething() 
{ 
} 

Теперь, второй и третий ошибок emited, потому что вы не включили типа параметра fileName в определении функции. На основе кода, он должен быть строкой:

int doSomething(string fileName) 
{ 
} 

Я также заметил, что, в то время как эта функция возвращает int, вы не используете это возвращаемое значение. Тем не менее, не забывайте return что-то от doSomething, иначе это вызовет неопределенное поведение.

+0

Спасибо, что работал только один последний вопрос. Выше выходов программы, таких как 'file1.txt' ' file2.txt' '.' и' ..' В моей папке есть только два файла, которые выводят два дополнительных значения. и '..' – ronroo

+1

@ronroo, '.' является« текущей папкой »и' ..' является папкой, содержащей текущую папку ». – SingerOfTheFall

+0

Можно ли это избежать? это может повлиять на дальнейшую работу. – ronroo

1

Да, Boost отлично, но это немного вздор. Так, только для completenessapplied для чтения изображений в каталоге для OpenCV:

// you need these includes for the function 
//#include <windows.h> // for windows systems 
#include <dirent.h> // for linux systems 
#include <sys/stat.h> // for linux systems 
#include <algorithm> // std::sort 
#include <opencv2/opencv.hpp> 
#include <iostream> //cout 

using namespace std; 

/* Returns a list of files in a directory (except the ones that begin with a dot) */ 
int readFilenames(std::vector<string> &filenames, const string &directory) 
{ 
#ifdef WINDOWS 
    HANDLE dir; 
    WIN32_FIND_DATA file_data; 

    if ((dir = FindFirstFile((directory + "/*").c_str(), &file_data)) == INVALID_HANDLE_VALUE) 
     return; /* No files found */ 

    do { 
     const string file_name = file_data.cFileName; 
     const string full_file_name = directory + "/" + file_name; 
     const bool is_directory = (file_data.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) != 0; 

     if (file_name[0] == '.') 
      continue; 

     if (is_directory) 
      continue; 

     filenames.push_back(full_file_name); 
    } while (FindNextFile(dir, &file_data)); 

    FindClose(dir); 
#else 
    DIR *dir; 
    class dirent *ent; 
    class stat st; 

    dir = opendir(directory.c_str()); 
    while ((ent = readdir(dir)) != NULL) { 
     const string file_name = ent->d_name; 
     const string full_file_name = directory + "/" + file_name; 

     if (file_name[0] == '.') 
      continue; 

     if (stat(full_file_name.c_str(), &st) == -1) 
      continue; 

     const bool is_directory = (st.st_mode & S_IFDIR) != 0; 

     if (is_directory) 
      continue; 

//  filenames.push_back(full_file_name); // returns full path 
     filenames.push_back(file_name); // returns just filename 
    } 
    closedir(dir); 
#endif 
    std::sort (filenames.begin(), filenames.end()); //optional, sort the filenames 
    return(filenames.size()); //Return how many we found 
} // GetFilesInDirectory 


void help(const char **argv) { 
    cout << "\n\n" 
     << "Call:\n" << argv[0] << " <directory path>\n\n" 
     << "Given a directory of images, create a vector of\n" 
     << "their names, read and display them. Filter out\n" 
     << "non-images\n" 
     << endl; 
} 

int main(int argc, const char** argv) 
{ 
    if(argc != 2) { 
     cerr << "\nIncorrect number of parameters: " << argc << ", should be 2\n" << endl; 
     help(argv); 
     return -1; 
    } 
    string folder = argv[1]; 
    cout << "Reading in directory " << folder << endl; 
    vector<string> filenames; 

    int num_files = readFilenames(filenames, folder); 
    cout << "Number of files = " << num_files << endl; 
    cv::namedWindow("image", 1); 
    for(size_t i = 0; i < filenames.size(); ++i) 
    { 
     cout << folder + filenames[i] << " #" << i << endl; 
     cv::Mat src = cv::imread(folder + filenames[i]); 

     if(!src.data) { //Protect against no file 
      cerr << folder + filenames[i] << ", file #" << i << ", is not an image" << endl; 
      continue; 
     } 
     cv::imshow("image", src); 
     cv::waitKey(250); //For fun, wait 250ms, or a quarter of a second, but you can put in "0" for no wait or -1 to wait for keypresses 
     /* do whatever you want with your images here */ 
    } 
} 
Смежные вопросы