Hallo together,
I want to read out all names of files with *.txt of one folder. These names have to be saved in an array so that I can use this array to work with.
Can someone please help me with this array?
Thanks in advance.
Every operating system handles file directories a little differently so C doesn't really include much to help you with this. However; the Windows API has just what you need and more...
Study the MSDN information for
SetCurrentDirectory(),
FindFirstFile(),
FindNextFile() and
FindClose() also take a look at the struct
WIN32_FIND_DATA ... you will need to understand all these to make this work.
PellesC also has a group of non-standard C functions you can use. For these you need to look at the dirent.h header in the help file.
(help -> Contents -> Private #include files -> Dirent.h)
I would suggest you learn the Windows way because it is faster and provides more information (File size, attributes, last modification date, creation date, and more).
The basic sequence is ...
- Create an instance of WIN32_FIND_DATA.
- Create a HANDLE to hold your search handle.
- Set your current directory to the folder that holds the files.
- Call FindFirstFile() to initiate your directory search.
- Begin a do/while loop in which you deal with your files.
- Do what you need to do with your file....
- Loop back to step 5 repeatedly calling FindNextFile()
- When done call FindClose() to destroy the search handle.
Ok that sounds really complicated but it isn't...
Here's an example that prints mp3 filenames on the screen from d:\myfolder\music
#define WIN32_DAFAULT_LIBS // automatically find libraries
#include <stdio.h>
#include <windows.h>
// entry point
int main (void)
{
WIN32_FIND_DATA fd; // directory data
HANDLE fh; // find handle
// set the working directory
SetCurrentDirectory("D:\\MyFolder\\Music");
// start the search
fh = FindFirstFile("*.mp3",&fd)
// deal with the results
do
{
printf("%s\n",fd.cFileName); // here is where you process the files
}
while (FindNextFile(fh,&fd) != 0); // exits when no more files
// close the find handle
FindClose(fh);
return 0;
}
For the most part it's better to deal with each file separately on the fly, inside the do/while loop than to try to harvest a linked list or array of filenames (the former is complicate, the latter has to be of a fixed size). By working on the fly, you can call a function, put extra code in there whatever you need.
Hope that helps.