0

I have created this function. In txt directory I have txt files. I try to loop the directory and open the txt files to edit them. When line is empty, it should be replaced by text contain number of occurrence count empty line.

// reading a text file
#include <iostream>
#include <fstream>
#include <string>
#include <sstream>
#include <dirent.h>
#include <boost/algorithm/string/replace.hpp>

int main () {
  std::stringstream stream;
  std::string content;
  std::string path = "U:\\C\\NBK\\txt";
  DIR *dir;
  struct dirent *ent;

  if ((dir = opendir (path.c_str() )) != NULL)
    {
    while ((ent = readdir (dir)) != NULL)
        {
        int c = 0;
        std::stringstream cStr;
        printf ("%s\n", ent->d_name);
        std::string tmp = path + "\\" + ent->d_name;
        std::ifstream ifs( tmp.c_str() );
        std::string line;
        if (ifs.is_open())
          while ( ifs.good() )
             {
             getline (ifs, line);
             if ( line.length() == 0) {
                 c++;
                 cStr << c;
                 line = line + "<h3>"  + cStr.str() + "<h3>";
                 }
             std::cout << line << std::endl;
            } // end while getline
        else
            std::cout << "Unable to open file\n";
        } // end while readdir
      closedir (dir);
    }
  else
    {
       perror ("File open failed");
      return 0;
    }
  return 0;
}

I can run the program from menu Build: Run. The problem is when I try to debug it. The program crashes in Code::Blocks, C++98 because of SIGSEGV. Stopped on the second line of following part:

if ((dir = opendir (path.c_str() )) != NULL) {
      while ((ent = readdir (dir)) != NULL) {

The Build Target is selected as Debug.

Pls explain what is going on here and how to fix it to debug it.

John Boe
  • 3,016
  • 10
  • 32
  • 56
  • Unrelated to your problem, but I suggest you take some time to read [Why is iostream::eof inside a loop condition considered wrong?](https://stackoverflow.com/questions/5605125/why-is-iostreameof-inside-a-loop-condition-considered-wrong). Using e.g. `!ifs.eof()` or `ifs.good()` as loop condition is the same. – Some programmer dude Aug 19 '17 at 09:44
  • 1
    Strange how you use Windows-like file path, yet are getting `SIGSEGV`. – user7860670 Aug 19 '17 at 09:48
  • First, check the entry to make sure it is a file (not a directory) and then, a txt file (if there are other files in the directory); then, start reading it. When you are done reading the file, close it. – Blackberry Aug 19 '17 at 10:22
  • Guys I have found the problem. The guy who commented the problem is in the `closedir (dir);` inside a loop was right. I have overlooked that the dir is the main dir path not the current file path. So I have moved the `closedir (dir);` outside of the second while loop and now everything works. So if you read it, you can put your answer and I will accept it. Thank you for your time. – John Boe Aug 19 '17 at 11:33

0 Answers0