How to make so that after reading a file "txt" it read another one then

Asked

Viewed 1,854 times

2

How to do after reading the file txt check if you have a next file txt, I know to read the file is enough:

ifstream Arquivo;
Arquivo.open("teste.txt");
while ()
{
   // leitura
}

After reading this file, check if you have another file, if you have it will read this file, and so on.

  • These files will be in the same folder as the executable?

  • yes, or it would be better to create a folder there even with that files?

  • It will depend on what you want, but as a matter of organization, having a proper directory for these files should be more suitable.

  • fully agree .

  • It is not very clear in your question what the real problem is. Why simply do ifstream Arquivo1, Arquivo2; Arquivo1.open("teste.txt"); Arquivo2.open("teste2.txt"); doesn’t fit? Did you mean that you don’t know how to find the next file/list files in a folder (something like this SOEN question: http://stackoverflow.com/questions/612097/how-can-i-get-the-list-of-files-in-a-directory-using-c-or-c)?

  • @Luizvieira can only have or no more two file, the user plays five file, so it has to be something generic to read the txt files

  • But the problem is not reading the files, but rather listing them for the read function, right?

  • @Luizvieira really , when reading one he will check if he has another file, if he has it he will read this file, and so on.

  • Okay, then edit the question to make it clearer. :)

Show 4 more comments

2 answers

4

Another way, as suggested on the SOEN issue that I mentioned in the comments, is to use the header "dirent. h". It is standard in Unix and can be downloaded from Windows (and used together with your project - just have the header file dirent.h). Thus, your code becomes more independent of the operating system.

An example of use:

#include <iostream>
#include <fstream>
#include <string>
#include <vector>

#include "dirent.h"

using namespace std;

vector<string> listfiles(char *sPath)
{
    vector<string> vRet;
    DIR *pDir = opendir(sPath);
    if(pDir != NULL)
    {
        struct dirent *pEnt;
        while((pEnt = readdir(pDir)) != NULL)
        {
            if(strcmp(pEnt->d_name, ".") != 0 && strcmp(pEnt->d_name, "..") != 0)
                vRet.push_back(pEnt->d_name);
        }
        closedir(pDir);
    }
    return vRet;
}

int main(void)
{
    vector<string> vFiles = listfiles("c:/teste/");
    char sFile[256];

    for(unsigned int i = 0; i < vFiles.size(); i++)
    {
        sprintf_s(sFile, 256, "c:/teste/%s", vFiles[i].c_str());

        ifstream oFile(sFile);
        string sData;

        getline(oFile, sData);

        printf("1a linha do arquivo {%s}: [%s]\n", sFile, sData.c_str());
    }

    return 0;
}

3


One way to list files is through functions FindFirstFile and FindNextFile (Windows):

#include <windows.h> /* Para usar as funções de busca de arquivos */
#include <vector>    /* Para usar */
#include <sstream>   /* Para usar o Stringstream */
#include <iostream>  /* Para manipular a entrada/saída de streams */
#include <fstream>   /* Para usar o ifstream */
....
using namespace std;
...
vector<string> ProcurarArquivos(string diretorio) {
    vector<string> arquivos;                      /* Vetor que irá armazenar os resultados temporários */
    string busca = diretorio + "\\*.txt";         /* Cria o filtro, no diretório será encontrado somente arquivos .txt */
    HANDLE hFind;                                 /* Identificador da pesquisa */
    WIN32_FIND_DATA data;                         /* Estrutura que conterá informações dos arquivos */
    hFind = FindFirstFile(busca.c_str(), &data);  /* Procura pelo primeiro arquivo */
    if (hFind != INVALID_HANDLE_VALUE) {          /* Se a função não falhar */
        do {
            arquivos.push_back(data.cFileName);   /* Armazena no vetor o nome do arquivo encontrado */
        } while (FindNextFile(hFind, &data));     /* Procura pelo próximo arquivo */
    FindClose(hFind);                             /* Fecha o identificador da pesquisa */
    }
    return arquivos;                              /* Retorna o vetor como resultado */
}

To read the contents of the file and return in a string, do:

string LerAquivo(string arquivo) {
    ifstream ifs;                                          /* Stream usada para fazer operações em arquivos */
    ifs.exceptions (ifstream::failbit | ifstream::badbit); /* Define quais exceções podem ser lançadas */
    try {                                                  /* Tenta executar o código abaixo */
        ifs.open(arquivo.c_str());                         /* Abre o arquivo */
        stringstream ss;                                   /* Stringstream que vai conter o resultado */
        ss << ifs.rdbuf();                                 /* Lê o buffer do stream e coloca no Stringstream */
        string str = ss.str();                             /* Coloca numa string o resultado do Stringstream */
        return str;                                        /* Retorna a string */
    }
    catch (ifstream::failure e) {                          /* Se houver erros em relação a leitura dos arquivos */
                                                           /* Fazer alguma coisa aqui caso ocorram erros */
        return "";                                         /* Retorna uma string vazia */
    }
}

To get the application path use the function GetModuleFileName:

string DiretorioDaAplicacao() {
    char buffer[MAX_PATH];                        /* Cria um buffer com tamanho máximo para um diretório */
    GetModuleFileName(NULL, buffer, MAX_PATH);    /* Para retornar o caminho completo do executável */
    int pos = string(buffer).find_last_of("\\/"); /* Captura a posição da última barra "/" */
    return string(buffer).substr(0, pos);         /* Extraí tudo desde o início até o ponto onde foi encontrado a barra "/" */
}

To extract only the file name, use the function:

string ExtrairNomeDoArquivo(string caminho) {
    int indice = caminho.rfind('/');              /* Encontra o índice da última ocorrência da barra "/" */
    return caminho.substr(indice + 1);            /* Extraí tudo a partir do índice da barra "/" */
}

Note: Works only on Windows, and there are times when this function may fail.

Example of use:

int main() {
    string Diretorio = DiretorioDaAplicacao();             /* Captura o diretório da aplicação */
    vector<string> arquivos = ProcurarArquivos(Diretorio); /* Cria um vetor que armazenará os o caminho dos arquivos encontrados */
    for (vector<string>::iterator i = arquivos.begin(); i != arquivos.end(); i++) { /* Faz a iteração sobre o vetor "arquivos" */
            string conteudo = LerAquivo(*i);               /* Coloca na variável o conteúdo do arquivo atual da iteração */
            string arquivo  = ExtrairNomeDoArquivo(*i);    /* Coloca na variável somente o nome do arquivo atual da iteração */

            cout << "Nome do arquivo: " << arquivo << endl;
            cout << conteudo << endl;
    }
    cin.get(); /* Espera o usuário digitar algo*/
    return 0;  /* Termina o programa */
}
  • a doubt did not understand the part of listing the files, I will list the files and only then I will do the reading. that’s right?

  • @Rodolfo The idea is this yes. You first list the files .txt from your directory, then in a for you read file by file.

  • I’m finding problem in for and in the LerArquivo() in the int main()

  • @Rodolfo What problem exactly?

  • @Rodolfo had forgotten to quote the header fstream that was necessary, try to run this code: http://pastebin.com/UtGsxZ03, it will just list the files .txt of your application folder.

  • @Rodolfo It worked out?

  • it worked however as I will do to read the data of that files?

  • 1

    @Rodolfo Just call the function LerArquivo with the argument *i, which is the current iteration file, example: http://pastebin.com/Kbt6ZF1P.

  • It would be like the part that searches the archives txt take the name and store in a type vector char nomeArquivo [50].

  • @Rodolfo You already have the path of the files in the vector arquivos, if you need to extract the name, you search for the last /, and with the substr, you extract the name of that file from the index. Example: http://pastebin.com/tqHN3yUc. It’s not something 100% safe, and only works on Windows, If you need something more elaborate, create a new question about it. =)

  • @qmechaik is working right, but it is difficult to understand the code, for not having much knowledge, I do not know would have to comment line by line on the part of listing the files, or would not have a simpler alternative to perform this same task.

  • @Rodolfo I edited the answer, I tried to comment as much as I could. See if you can understand now.

Show 7 more comments

Browser other questions tagged

You are not signed in. Login or sign up in order to post.