0

My souce is below.
function is called from main program.
But during execution segmentation fault occur.
If I execute half are ok, but half are failed.
I used kdb. But still I don't know why.
I think I used correct expression.
kdb said "if(entry->d_type) == DT_REG) " is problem.
I think entry->d_type part is problem. I don't know. WIll you help me?
I appreciate all of you.
======================================

#include <stdio.h>
#include <getopt.h>
#include <iostream>
#include <dirent.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <errno.h>
#include <string.h>
#include <fstream>
#include <limits.h>

using namespace std;

void listdir()
{
    	//size_t size;
    	//char *path = new char[1024]; 
    	//path = getcwd(path,size);

	DIR *pdir;  //Open directory variable
	struct dirent *entry;   //Directory read structure 
	struct stat statbuf;    //File inode information structure
	
	pdir = opendir("./");

	//ofstream syswrite;
	//syswrite.open ("inoresult.dat");
	
	if(!pdir) {
		cout << "Could't open working directory" << endl; }

	while ((entry = readdir(pdir)) != NULL)  
	{
		entry = readdir(pdir);
		cout << entry->d_ino << endl;		
	    		if((entry->d_type) == DT_REG)  {
			
			syswrite << "file         "<< entry->d_ino << "     " << entry->d_name << endl; }

	    		else if((entry->d_type) == DT_DIR)  {
				cout << "directory    "<< entry->d_ino << "     " << entry->d_name << endl; 
				syswrite << "directory    "<< entry->d_ino << "     " << entry->d_name << endl;   }
	    		else if((entry->d_type) == DT_LNK) 
			{
				cout << "link         "<< entry->d_ino << "     " << entry->d_name << endl;   
				syswrite << "link         "<< entry->d_ino << "     " << entry->d_name << endl;   
			}
     	    		cout << "=======================================" << endl;
		} 
	}	
        closedir (pdir);
	syswrite.close();

}

Edited by WaltP: Added CODE tags -- with all the help about them, how could you miss using them????

2
Contributors
1
Reply
3
Views
7 Years
Discussion Span
Last Post by nezachem
0

Use code tag please.

Now:

while ((entry = readdir(pdir)) != NULL)
{
entry = readdir(pdir);
cout << entry->d_ino << endl;
if((entry->d_type) == DT_REG) {

You shouldn't do the second readdir. The way your code is written, you throw away every even entry. If the number of entries is even, your program sort of works (at least it doesn't crash). If the number of entries is odd, a readdir in a while condition returns a valid entry, a subsequent readdir (at line 3) returns NULL, and you have your segfault.

Edited by happygeek: fixed formatting

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.