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();

}

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.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.