write the name of a file in .txt doc

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
1
2
movie.avi
song.mp3
thx very much
You'll need to read the files in the directory, open your names.txt and write them.

Do you know how to write a file or how to read the filenames in a directory?
man i'm just giving an example i'm having a folder that has 2174 files and i need to write their names in a text file
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>

using namespace 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.
Last edited on
10x very much btw it is working
Topic archived. No new replies allowed.