-2

First of all, I'm a complete novice at programming, especially in C. The example I'm going to show is code I've snagged from this site and kicked until it didn't quite do what I wanted. :)

Second, I'm using a dual-core Celeron with Linux Mint and the GNU C Compiler.

What I want to do is list the subdirectories within a directory, skipping the parent directory if any. Unfortunately, the code I have doesn't work. I tried strcpy and strncpy, but I couldn't figure out how to use them and I just screwed up the code so that I got a "segmentation fault" when I tried to run the program.

Here's the code:

/*
 * This program displays the names of all files in the current directory.
 */

#include <dirent.h>
#include <string.h>
#include <stdio.h>

int main(void)
{
    DIR           *d;
    struct dirent *dir;
    char dirname[255];
    d = opendir(".");
    if (d)
    {
        while ((dir = readdir(d)) != NULL)
        {
            if (dir->d_type == DT_DIR) 
            {
                strncpy(dirname, dir->d_name, 254);
                dirname[254] = '\0';
                if (dirname != "..") /* I want to skip this, but it doesn't work */
                {
                    printf ("%s\n", dirname);
                }
            }
        }


        closedir(d);
    }

    return(0);
}

Thanks for any help you can give. I'd especially be interested in links to sites that can offer tutorials that would help me with this little project, as I want a better understanding of what the heck I'm doing. :)

Bill Lynch
  • 80,138
  • 16
  • 128
  • 173
  • `if (dir->d_type == DT_DIR) { if (strcmp(dir->d_name, "..") != 0) { printf("%s\n", dir->d_name); } }` – melpomene Nov 07 '15 at 16:59
  • 1
    If you want to understand what you're doing, start from the beginning! – t0mm13b Nov 07 '15 at 17:00
  • Possible duplicate of [How to compare strings in C for a condition](http://stackoverflow.com/questions/14779112/how-to-compare-strings-in-c-for-a-condition) – Jongware Nov 07 '15 at 17:07

1 Answers1

0

In C, to compare strings you need to use either strcmp or strncmp.

if (strcmp(dirname, "..") != 0) { ... }
Bill Lynch
  • 80,138
  • 16
  • 128
  • 173
  • Ah, so that's how to use it! :) Makes perfect sense when shown, but the example in the tutorial I was using was doing something totally different, so I couldn't apply it. Many thanks. – Matt Roberts Nov 09 '15 at 19:36