Jump to content





Recent Status Updates

  • Photo
      16 Apr
    Kadence

    If you're reading this, you're on my profile and I know you're on my profile because I'm probably viewing yours.

    Show comments (6)
  • Photo
      10 Apr
    Poe

    Finally (and hopefully) i'm getting a team together that knows a little of this and a little of that; and maybe all my open source projects that are half written can begin to be released. :)

View All Updates
Photo
- - - - -

Read all files in a folder


  • Please log in to reply
13 replies to this topic

#1 Silvestros

Silvestros

    CC Newcomer

  • Just Joined
  • PipPip
  • 12 posts

Posted 13 November 2010 - 10:07 AM

Hello friends,

I have a folder with txt files. I want to open these files one by one, but can't understand how to do it. Searching the internet I found examples with FindFirstFile() and FindNextFile() but can't get them to work.
If it matters, I use windows 7.

Thank you in advance!
  • 0

#2 Flying Dutchman

Flying Dutchman

    Programming God

  • Expert Member
  • PipPipPipPipPipPipPip
  • 1,043 posts
  • Location:::1
  • Programming Language:C++, Python

Posted 13 November 2010 - 11:38 AM

#include <dirent.h>
#include <string>
#include <vector>

std::vector<std::string> open(std::string path = ".") {

    DIR*    dir;
    dirent* pdir;
    std::vector<std::string> files;

    dir = opendir(path.c_str());

    while (pdir = readdir(dir)) {
        files.push_back(pdir->d_name);
    }
    
    return files;
}
This will list all files in directory you pass as argument in STL vector and return it. You then just iterate throu that vector and open file(s).
int main() {

    std::vector<std::string> f;

    f = open(); // or pass which dir to open

    std::fstream file;

    file.open(f[0]);

    return 0;
}

A while ago I made myself a wrapper class for directory manipulation, object oriented way. If you want the code, I'll post it.
  • 1
The roots of education are bitter, but the fruit is sweet.

#3 Silvestros

Silvestros

    CC Newcomer

  • Just Joined
  • PipPip
  • 12 posts

Posted 13 November 2010 - 12:00 PM

First of all, thank you for replying!

I ran your code but it throwed an error (visual studio 2010):

error C1083: Cannot open include file: 'dirent.h': No such file or directory
  • 0

#4 Flying Dutchman

Flying Dutchman

    Programming God

  • Expert Member
  • PipPipPipPipPipPipPip
  • 1,043 posts
  • Location:::1
  • Programming Language:C++, Python

Posted 13 November 2010 - 12:13 PM

Microsoft Visual C++ does not include dirent.h

Bummer!. I don't know how to work with dir's in VC++ but this looks promesing.
  • 0
The roots of education are bitter, but the fruit is sweet.

#5 mnirahd

mnirahd

    CC Addict

  • Senior Member
  • PipPipPipPipPip
  • 328 posts

Posted 13 November 2010 - 02:31 PM

Hi,

The above code should help you in case if you're working on UNIX. On a windows version you should use FindFirstFile & FindNextFile functions which are Win32 API functions.

An example, how to list .txt file in a given directory, consider the following code.

#include "stdafx.h"
#include <windows.h>
#include <tchar.h>
#include <stdio.h>

int main(int argc, char *argv[])
{
	WIN32_FIND_DATA FindFileData;
	HANDLE hFind;

        [COLOR="Red"][B]//Dont' forget you change this directory with one you want to traverse![/B][/COLOR]
	TCHAR  *directory = TEXT("G:\\Work");
	TCHAR patter[MAX_PATH];

	memset(patter, 0x00, MAX_PATH);
	_stprintf(patter, TEXT("%s\\*.txt"), directory);
	hFind = FindFirstFile(patter, &FindFileData);
	if (hFind == INVALID_HANDLE_VALUE) 
	{
		printf ("FindFirstFile failed (%d)\n", GetLastError());
		return 1;
	} 
	else 
	{
		do
		{
			//ignore current and parent directories
			if(_tcscmp(FindFileData.cFileName, TEXT("."))==0 || _tcscmp(FindFileData.cFileName, TEXT(".."))==0)
				continue;

			if(FindFileData.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)
			{
				//ignore directories
			}
			else
			{
				//list the Files

				_tprintf (TEXT("%s\n"), 
					FindFileData.cFileName);
			}
		}
		while (FindNextFile(hFind, &FindFileData));
		FindClose(hFind);
	}

	return 0;
}



I hope this helps!

Munir
  • 0

#6 Silvestros

Silvestros

    CC Newcomer

  • Just Joined
  • PipPip
  • 12 posts

Posted 14 November 2010 - 02:54 PM

@Flying Dutchman: Maybe it's posible to run your code with cygwin, if my project wasn't in visual studio. I'll check the link you posted and try it if something go wrong with mnirahd's solution. Thank you very much!

@mnirahd: Hello my friend! I think that is exactly what I need. I changed the directory with one that contains only 5 txt files, but for some reason the program enters the first IF and prints the message: FindFirstFile failed (3)
Could you tell me why this would happen? And why 3? I think something goes wrong with _stprintf() and I don't know what exaclty this function does.
I really appreciate your help!
  • 0

#7 mnirahd

mnirahd

    CC Addict

  • Senior Member
  • PipPipPipPipPip
  • 328 posts

Posted 14 November 2010 - 09:16 PM

Hi,

The description of the error code 3 return from FindFirstFile is

//define error code if given path is wrong or doesn't exists
#define ERROR_PATH_NOT_FOUND             3L

This means that you're not passing a correct path. Please can you double check it. If you're confused with _stprintf, then try

#include "stdafx.h"
#include <windows.h>
#include <tchar.h>
#include <stdio.h>

#define ERROR_SUCCESS 89
int main(int argc, char *argv[])
{
	WIN32_FIND_DATA FindFileData;
	HANDLE hFind;

[COLOR="Red"]        //NOTE: write here complete name of your directory and append \\*.txt to filter the txt files only in findfirstfile and findnextfile functions!
[/COLOR]	TCHAR  *directory = TEXT("G:\\Work\\*.txt");
	hFind = FindFirstFile(directory, &FindFileData);
	if (hFind == INVALID_HANDLE_VALUE) 
	{
		printf ("FindFirstFile failed (%d)\n", GetLastError());
		return 1;
	} 
	else 
	{
		do
		{
			//ignore current and parent directories
			if(_tcscmp(FindFileData.cFileName, TEXT("."))==0 || _tcscmp(FindFileData.cFileName, TEXT(".."))==0)
				continue;

			if(FindFileData.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)
			{
				//ignore directories
			}
			else
			{
				//list the Files

				_tprintf (TEXT("%s\n"), 
					FindFileData.cFileName);
			}
		}
		while (FindNextFile(hFind, &FindFileData));
		FindClose(hFind);
	}

	return 0;
}

I hope this helps

Munir
  • 0

#8 Silvestros

Silvestros

    CC Newcomer

  • Just Joined
  • PipPip
  • 12 posts

Posted 15 November 2010 - 12:52 PM

You're right, I pasted my directory with single back slashes. Now it works and prints the names of the txt files.
My last problem is how can I open these files one by one (or put them in a linked list with items FILE so I can open them later). I need the text that these files contain. Thank you again for the help and sorry if I'm pain in the @ss.
  • 0

#9 mnirahd

mnirahd

    CC Addict

  • Senior Member
  • PipPipPipPipPip
  • 328 posts

Posted 15 November 2010 - 01:12 PM

Hi,

You can try the following code:


#include "stdafx.h"
#include <windows.h>
#include <tchar.h>
#include <stdio.h>
#include <stdlib.h>

int main(int argc, char *argv[])
{
	WIN32_FIND_DATA FindFileData;
	HANDLE hFind;

[COLOR="Red"]        //Dont' forget you change this directory with one you want to traverse!
[/COLOR]	TCHAR  *directory = TEXT("G:\\Work");
	TCHAR patter[MAX_PATH];
        TCHAR fileName[MAX_PATH];
	memset(patter, 0x00, MAX_PATH);
	_stprintf(patter, TEXT("%s\\*.txt"), directory);
	hFind = FindFirstFile(patter, &FindFileData);
	if (hFind == INVALID_HANDLE_VALUE) 
	{
		printf ("FindFirstFile failed (%d)\n", GetLastError());
		return 1;
	} 
	else 
	{
		do
		{
			//ignore current and parent directories
			if(_tcscmp(FindFileData.cFileName, TEXT("."))==0 || _tcscmp(FindFileData.cFileName, TEXT(".."))==0)
				continue;

			if(FindFileData.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)
			{
				//ignore directories
			}
			else
			{
				//list the Files

				_tprintf (TEXT("%s\n"), 
                                
					FindFileData.cFileName);
[COLOR="Red"]                                 memset(fileName, 0x00, sizeof(fileName));
                                 _stprintf(fileName, TEXT("%s\\%s"), directory, FindFileData.cFileName);
                                 FILE *fptr = fopen(fileName, "r");
                                 //do here whatever you want to do..
                                 fclose(fptr);
[/COLOR]			}
		}
		while (FindNextFile(hFind, &FindFileData));
		FindClose(hFind);
	}

	return 0;
}

I hope this helps

Munir
  • 0

#10 Silvestros

Silvestros

    CC Newcomer

  • Just Joined
  • PipPip
  • 12 posts

Posted 15 November 2010 - 01:33 PM

there is an issue with fopen:
error C2664: 'fopen' : cannot convert parameter 1 from 'TCHAR [260]' to 'const char *'
  • 0

#11 mnirahd

mnirahd

    CC Addict

  • Senior Member
  • PipPipPipPipPip
  • 328 posts

Posted 15 November 2010 - 02:27 PM

Hi,

Hi,

Ok, please usre _tfopen instead of fopen. try that and let me know how does that go

_tfopen((const TCHAR *)fileName, TEXT("r"));

Munir
  • 0

#12 Silvestros

Silvestros

    CC Newcomer

  • Just Joined
  • PipPip
  • 12 posts

Posted 15 November 2010 - 03:06 PM

That works! Thank you for being so patient and helpful! You just rock!
  • 0