i want to make a program that prints the names of the files in a text doc. for example in C:/test/ there are movie.avi and song.mp3 and the program creates names.txt and fills it with
I am pretty sure that kbw didn't mean to manually read the files and write them in a file.
If this is something you want to do just once, you can do this with a simple command in terminal:
Windows: dir /b > names.txt
Linux/OS X: ls > names.txt
If you need to do this in C++ you can do the following
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
#include <fstream>
#include <dirent.h>
usingnamespace std;
int main() {
ofstream outfile("names.txt");
DIR *directory;
struct dirent *file;
directory = opendir("c:/test/");
while (file = readdir(directory)) {
outfile<<file->d_name<<endl;
}
}
In this example, directory is a pointer to the directory you are looking into and file a pointer to each file as you iterate through them. readdir(directory) will return the next file each time you call it or null if there aren't any more files in the directory.
Some things to take note of. readdir returns hidden and special files too (like . and ..), so you might want to check for them if you don't want them in names.txt. readdir returns both files and folders. You can check file.d_type if you don't want both. Files will have file.d_type = 4 and folders file.d_type = 8.