I’m trying to check if a file is a folder but when I change this line:
snprintf(buf, sizeof buf, "%s\\%s", path, e->d_name);
^ ^
+------+ note the differences
To this:
snprintf(buf, sizeof buf, "%s\b%s", d->dd_name, e->d_name);
^ ^
+------+ note the differences
It does not print “is folder” or “is file” because stat(...) fails. Although both lines generate same output path.
Whats going on?
The code:
#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <dirent.h>
int main(int argc, char** argv) {
DIR *d;
struct dirent *e;
struct stat fs;
char*path = "C:\\Users\\Me\\Documents\\NetBeansProjects\\MyApp";
d = opendir(path);
if (d != NULL) {
while (e = readdir(d)) {
char buf[256];
snprintf(buf, sizeof buf, "%s\\%s", path, e->d_name); // <- here
printf("%s\n",buf);
if (stat(buf, &fs) < 0) continue;
if (S_ISDIR(fs.st_mode)) {
printf("is folder");
} else {
printf("is file");
}
}
closedir(d);
}
return 0;
}
The advice from Mat is sound; there are no documented publicly accessible members in a
DIRstructure, and you should not be trying to used->dd_name, therefore.However, if you want to remove an asterisk from the end of a string, then you cannot use backspace to do that. A backspace only erases a character when typed at a terminal. Otherwise, it is just a control character in a string. You could use:
This would omit the last character from the
d->dd_namestring (leaving, I assume, a trailing slash or backslash). Note that the cast is necessary whensizeof(size_t) > sizeof(int)(as on 64-bit Unix systems); the value consumed by the*is anint.