How can I read .txt files in directory with c++?

Hi, i want to read txt files in a directory and after, ı want to put these files into a list. How can I?
Hello mfatihkoseoglu,

Based on your question, lack of code and the fact that no one reading this post has any idea what you know. You could start with http://www.cplusplus.com/doc/tutorial/ or post what code you have written so anyone read this will have some idea what you have done.

Also post the input file so everyone will be know what you have to work with and will be using the same information. How the input file is laid out will determine how you will need to read the file.

If you are not familiar with working with files you may find this helpful:
1
2
3
4
5
6
7
8
9
10
	const std::string inFileName{ "" };  // <--- Put full file name here and path if needed.

	std::ifstream inFile(inFileName);

	if (!inFile)
	{
		std::cout << "\n File \"" << inFileName << "\" did not open" << std::endl;
		std::this_thread::sleep_for(std::chrono::seconds(3));  // <--- Needs header files chrono" and "thread".
		return 1;  //exit(1);  // If not in "main".
	}

Line 8 is optional. This is something I use you may not need it. Remove it if you want, but worth keeping for the future.

This is less than what I first used and could be shortened even more later, but useful when you are first starting.

Hope that helps,

Andy
Probably something like this:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
#include <filesystem>
#include <iostream>
#include <string>
#include <vector>

int main()
{
    std::cout << "Path to directory? ";
    std::string dirname;
    std::getline(std::cin, dirname);
    std::filesystem::path dirpath { dirname };

    std::vector<std::filesystem::directory_entry> entries;
    for( const auto& e : std::filesystem::directory_iterator(dirpath) ) {
        entries.push_back(e);
    }

    for (const auto& e : entries) {
        std::cout << e.path().filename() << '\n';
    }
}


I can’t compile it in my MinGw environment in W7, but I managed to conjure up a code which relies on the boost libraries:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
#include <boost/filesystem.hpp>
#include <iostream>
#include <string>
#include <vector>

int main()
{
    std::cout << "Path to directory? ";
    std::string dirname;
    std::getline(std::cin, dirname);
    boost::filesystem::path dirpath { dirname };

    std::vector<boost::filesystem::directory_entry> entries;
    for( const auto& e : boost::filesystem::directory_iterator(dirpath) ) {
        entries.push_back(e);
    }

    for (const auto& e : entries) {
        std::cout << e.path().filename() << '\n';
    }
}


I could compile the latter by this command:
g++ -std=c++2a -Wall -Wextra -Wpedantic -Ipath-to-your-boost-headers main.cpp -Lpath-to-your-boost-binaries -lboost_system -lboost_filesystem -o main.exe

Topic archived. No new replies allowed.