Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

linux c compile with ftw library

Tags:

c

linux

i have simple code:

  1 #include <ftw.h>
  2 #include <stdio.h>
  3 #include <stdlib.h>
  4 #include <string.h>
  5
  6 static int display_info(const char *fpath, const struct stat *sb, int tflag, struct FTW *ftwbuf){
  7     printf("%-3s %2d %711d  %-40s %d %s\n", tflag == FTW_D) ? "d" :
  8         (tflag == FTW_DNR) ? "dnr" : (tflag == FTW_DP) ? "dp" : (tflag == FTW_F) ? "f" :
  9         (tflag == FTW_DP) ? "dp" : (tflag == FTW_SL) ? "sl" : (tflag == FTW_SLN) ? "sln" : "?", ftwbuf->level, (long long) sb->st_size, fpath, ftwbuf->base, fpath + ftwbuf->base);
 10         return 0;
 11 }
 12
 13 int main (int argc, char ** argv){
 14     int flags = 0;
 15     if( argc > 2 && strchr(argv[2], 'd') != NULL) flags |= FTW_DEPTH;
 16     if( argc > 2 && strch(argv[2], 'p') != NULL) flags |= FTW_PHYS;
 17     nftw((argc < 2) ? "." : argv[1], display_info, 20, flags);
 18
 19     exit(EXIT_SUCCESS);
 20 }

and when i would like to compile:

gcc -o main main.c

i get some problems:

main.c:8: błąd: `FTW_DP, undeclared (first use in this function)

How i must compile (with some library or what?)

like image 505
cniak Avatar asked Mar 05 '26 12:03

cniak


2 Answers

You need to add

#define _XOPEN_SOURCE 500 

to the top of your code.

Here is a nice reference page:

http://man7.org/linux/man-pages/man3/ftw.3.html

like image 156
wilson Avatar answered Mar 07 '26 03:03

wilson


You have 3 solutions :

  1. Above #include <ftw.h>, add :

    #define _XOPEN_SOURCE 500
    #include <ftw.h>
    // ...
    
  2. (thx @alvits) In command line, add :

    gcc -D_XOPEN_SOURCE=500 ...
    
  3. Into your makefile :

    CPPFLAGS := -D_OXPEN_SOURCE=500 ...
    

Why do you need this define ?

From inside <ftw.h> and then <features.h> you can see :

#ifdef  _XOPEN_SOURCE
...
# if (_XOPEN_SOURCE - 0) >= 500
#  define __USE_XOPEN_EXTENDED  1

And in <ftw.h> :

#ifdef __USE_XOPEN_EXTENDED
/* These flags are only passed from the `nftw' function.  */
  FTW_DP,       /* Directory, all subdirs have been visited. */
# define FTW_DP  FTW_DP
like image 34
Chnossos Avatar answered Mar 07 '26 03:03

Chnossos



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!