Anil Kumar
Anil Kumar

Reputation: 79

get the list of source files from existing eclipse project using CDT

i am working on CDT eclipse plug in development, i am trying to get the list of sources files which exist in eclipse project explorer using CDT code using following code ,which results null.

Case1:

IFile[] files2 = ResourcesPlugin.getWorkspace().getRoot().findFilesForLocationURI(new URI("file:/"+workingDirectory));
for (IFile file : files2) {
   System.out.println("fullpath " +file.getFullPath());
}

Case2:

IFile[] files = ResourcesPlugin.getWorkspace().getRoot().findFilesForLocationURI(getProject().getRawLocationURI());
for (IFile file : files) {
   System.out.println("fullpath " +file.getFullPath());              
}

Case3:

IFile[] files3 = ResourceLookup.findFilesByName(getProject().getFullPath(),ResourcesPlugin.getWorkspace().getRoot().getProjects(),false);
for (IFile file : files3) {
   System.out.println("fullpath " +file.getFullPath());
}

Case4:

IFolder srcFolder = project.getFolder("src");

Case 1 ,2,3 giving me output null, where i am expecting list of files; in Case 4: i am getting the list of "helloworld/src" files, but i am expecting to get the files from the existing project mean main root ,ex:"helloworld" please suggest me on this.

Upvotes: 5

Views: 1555

Answers (1)

Eugene
Eugene

Reputation: 9474

You can either walk through the worspace resources tree using IResourceVisitor - or you can walk through CDT model:

private void findSourceFiles(final IProject project) {
    final ICProject cproject = CoreModel.getDefault().create(project);
    if (cproject != null) {
        try {
            cproject.accept(new ICElementVisitor() {

                @Override
                public boolean visit(final ICElement element) throws CoreException {
                    if (element.getElementType() == ICElement.C_UNIT) {
                        ITranslationUnit unit = (ITranslationUnit) element;
                        if (unit.isSourceUnit()) {
                            System.out.printf("%s, %s, %s\n", element.getElementName(), element.getClass(), element
                                    .getUnderlyingResource().getFullPath());
                        }
                        return false;
                    } else {
                        return true;
                    }
                }
            });
        } catch (final CoreException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
}

Note there may be more source files then you actually want (e.g. you may not care system about headers) - you can filter them by checking what the underlying resource is.

Upvotes: 4

Related Questions