Question:

C++ how to open multiple text files for manipulation?

by  |  earlier

0 LIKES UnLike

what i want to do is read in a text file at a time do some manipulation to it, then close and open another one and so on...

assuming that there are hundreds of files with different names, how can i attain a list of the text file names and then run them all

any sample code with explanation would really help thanks !

 Tags:

   Report

2 ANSWERS


  1. Hi

    Assuming that the files have a common extension ( .txt)

    You could write a temporary file with the files listed and then open each one like this:

    #include <stdio.h>

    #include <stdlib.h>

    #include <string.h>

    const char* tmpfl = "tmpfile";

    int main()

    {

       char cmd[21];

       char File[20];

       char Line[80];

       char txfile[80];

       FILE* fp;

       FILE* fp1;

       strcpy(cmd,"ls *.txt > ");

       strcat(cmd,tmpfl);

       //printf("cmd is %s\n",cmd);

       system(cmd);

       if (( fp = fopen(tmpfl,"r")) == NULL)

       {

          printf("Cannot open temporary file!\n");

          exit(1);

       }

       while ( fgets ( File ,sizeof(File),fp))

       {

           strcpy(txfile,"./");

           strcat(txfile,File);

           printf("File: %s",txfile);

           if (( fp1 = fopen(txfile,"r")) == NULL)

           {

              printf("Cannot open %s\n",txfile);

              continue;

           }

           while ( fgets ( Line , sizeof(Line), fp1) == NULL)

           {

              // Do something here

           }

           fclose(fp1);

       }

       fclose(fp);

       return 0;

    }

    This is 'C' sorry, but it shold give you some ideas

    Regards

    G


  2. If you're using Visual Studio, look at this:

    http://msdn.microsoft.com/en-us/library/...

    Specifically, FindFirstFile, FindNextFile, etc.  

Question Stats

Latest activity: earlier.
This question has 2 answers.

BECOME A GUIDE

Share your knowledge and help people by answering questions.