• 12
• 12
• 9
• 10
• 13

# Detect if file exists

This topic is 4497 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

## Recommended Posts

Up until now Ive always done "Input map to load: ", read what user wrote, open the file and load the data. But I want to do: "Which map do you want to play? [1] map1 [2] map2" and so on... The program lists all maps in the maps folder then the player just clicks with the mouse or presses one button and the map loads. Is there anyway to check for (txt) files in this way? To list all existing in a directory?

##### Share on other sites
GNU/Linux or Windows or ?
C++ or C# or ?

##### Share on other sites
FILE * file = fopen(filename, "rt");

if(file == null){
}

i think this would work, not 100% positive.

##### Share on other sites
Portable:
_findfirst
_findnext
_findclose

from <io.h>

OR

windows specific:

FindFirstFile
FindNextFile
FindClose

using <windows.h>

OR
also portable:
boost::filesystem

--edit: beaten :(

##### Share on other sites
Quote:
 Original post by AAAPFILE * file = fopen(filename, "rt");if(file == null){ file not found }i think this would work, not 100% positive.

But that way I would need to manually add all the files thats should be listed? I cannot just let the user place a new map in the mapfolder and have it appear in the maplist ingame?

##### Share on other sites

I believe, code to list files in a directory is platform specific, because it would have to access the filesystem through the operating system

##### Share on other sites
Those FindFirstFile() functions seems good, but can I put relative paths in there? Tried with "\\Maps\\" but it didnt work, works with full path though: "C:\\Project\\Maps".

##### Share on other sites
what if you just try "maps\" ?

and by the way, this will likely help you with the function
FindFileFirst() on msdn

##### Share on other sites
If you're using boost, you could use boost::filesystem's directory_iterator to retrieve all the entries in a directory.

The .leaf of a path is the rightmost part of a path delimited by '/', in this case the filename.

A directory_iterator starts on the first entry of the path and directory_iterator() is equivalent to the entry past the end of the directory.

The following code iterates over all the files in a folder and does something to them.

And yeah, it's portable to any platform the boost library works on, which is virtually all of them.

for(boost::filesystem::directory_iterator I("./Maps/"); I != boost::filesystem::directory_iterator(); ++I){	if(!boost::filesystem::is_directory(*I))	{		DoStuffWith(I->leaf());   // leaf() returns a path, which has implicit converters to and from std::string.	}}

The boost doc on ::filesystem