Warning with nftw - c

I'm trying to use the nftw to process some files under a directory
#include <ftw.h>
#include <stdio.h>
int wrapper(const char * fpath, const struct stat *sb, int typeflag, struct FTW *ftwbuf) {
printf("File %d\n", ftwbuf->base);
return(0);
}
int main(int argc, char ** argv) {
const char *name;
int flags = 0;
name = argv[1];
nftw(name, wrapper, 20, flags);
return 0;
}
When I'm compiling (gcc kconfig_parser.c -o parser) , I've got this warning and this error..
kconfig_parser.c:5: warning: ‘struct FTW’ declared inside parameter list
kconfig_parser.c:5: warning: its scope is only this definition or declaration, which is probably not what you want
kconfig_parser.c: In function ‘wrapper’:
kconfig_parser.c:6: error: dereferencing pointer to incomplete type
I've checked the definition of the struct and the prototype of the callback, and some examples, it should be fine... What am I doing wrong ? (I've removed almost everything of my code to clear it)...
thanks

Linux, for some reason, still uses SUSv1 for this API, where nftw() is still considered an extension.
From the Linux manual page, the include has to be:
#define _XOPEN_SOURCE 500
#include <ftw.h>

Hmm. Your code works for me. Check your include paths, maybe? Though this is a system header, so it should be pretty hard to miss this. Or were you accidentally compiling a version that didn't have the #include <ftw.h> line?
$ gcc -o ftw ftw.c
$ ./ftw my-directory
File 10
File 11
File 16
File 16
File 16
File 16
File 16
... etc ...
edit: The test above was done on Mac OS X. In a (now deleted) comment the OP mentioned he was on Debian, for which the man page mentions that #define _XOPEN_SOURCE 500 is necessary, as Juliano points out.

On a CentOs versions the header file didn't use "#define _XOPEN_SOURCE 500"
i had to do this below,
#define __USE_XOPEN_EXTENDED 1
#include <ftw.h>

On Ubuntu 18.04, this is what seems to work now (similar to CentOS as mentioned by JohnMeg).
#define __USE_XOPEN_EXTENDED 1
#include <ftw.h>

Related

C error: conflicting types for function and previous declaration was here (not duplicate)

Apologies for the dumb question. I checked all similar questions for the same error on stackoverflow, but it didn't help me understand why this error is happening in the following code.
I have one additional header file and a source file, which is included in the main file, and when I compile, I am getting the following error. I am trying to pass the char** argv from the main() to another function defined in another header file.
#include "include/Process.h"
#include <stdio.h>
#include <stdlib.h>
int main(int argc, char** argv) {
if (argc < 2) {
printf("Please provide a path to file\n");
return (EXIT_FAILURE);
}
Process(argv);
Process.h:
#pragma once
extern void Process(char** path);
Process.c:
#include <stdio.h>
#include "../include/Process.h"
#include <stdlib.h>
#include <sys/stat.h>
#include <syslog.h>
#include <sys/types.h>
#include <unistd.h>
void Process(char** path) {
printf("%s\n", path[1]);
}
It gets compiled but the warning is
./src/Process.c:22:6: error: conflicting types for ‘Process’
void Process(char** path) {
^
./include/Process.h:17:6: note: previous declaration of ‘Process’ was here
extern void Process(char** path);
^
However, the warning disappears when I change the type of path from char** to char* and pass argv[1] instead of argv.
I am clueless why this is happening like this, and according to
this similar post, I tried adding a forward declaration for char** path above extern void Process(char** path); in the Process.h file, but it didn't help either.
Why is this error thrown when using char** path?
Why it disappears when I use char* path?
So far, I am able to see the program running, even with this warning. Is it safe to ignore this warning? If not, what could be the possible effects it can have during runtime?
Using gcc version 4.9.2 (Ubuntu 4.9.2-10ubuntu13)
Thanks.
Try putting your custom includes after the system includes.
It might be possible that the custom include defines a macro which interferes with the system includes. To minimize the risk of this, I always put the Standard C includes first, then any OS includes, and then third party libraries, and then my own ones
In theory the custom include shouldn't do this, and the system includes should only use reserved names, but in practice this doesn't always happen.

Header and Source file problems in Code::Blocks

I am programming a game in C using Code::Blocks. I am using the most recent version of C and of Code::Blocks. I am still learning the language.
All of my past programs have been contained in one huge source file, so I decided to branch out and try putting my code in multiple files. I know that the proper way to do it is to have source files containing code definitions and such and a header file containing prototypes for other source files to use. This has worked out horribly for me and I either can't get the files to work together properly or it simply doesn't work period.
I have a single function in a source file called process.c and a function prototype in a file called process.h. I also have a main.h and a main.c containing all the rest of the code. The main issue is that I have a typedef struct Game in my main.h file and I can't get the 'Game' struct type I created to work in my process.c. Every function in my game needs the Game type in order to work. However, when I give process.c access to main.h (the file that Game is declared in) I get issues.
My code works fine when it's in one file. My header files are protected from duplication and are properly included in the program. The problem is, I need to include main.h in both main.c and process.c. And I have to include process.h in both 'main.c' and 'process.c'. I have tried every configuration and nothing works.
In some #include configurations I get no errors, but I get this weird message that says "It seems your project has not been built yet; would you like to build it now?" and when I click "Yes" nothing happens.
My compiler works fine and there is nothing wrong with the projects settings. What the heck is going on here? How do I get main.h and process.h to work together?
EDIT: Source code:
main.c:
#include <stdio.h>
#include "main.h"
#include "process.h"
void initGame(Game *thisGame)
{
variable = 10;
number = 5;
letter = 'c';
}
int main()
{
Game thisGame;
initGame(&thisGame);
displayData(&thisGame);
return 0;
}
main.h:
#ifndef _MAIN_H_
#define _MAIN_H_
typedef struct
{
int variable, number;
char letter;
}
#endif
process.c:
#include <stdio.h> //not sure if this should be here or not, it doesn't seem to effect my code
#include "main.h"
#include "process.h"
void displayData(Game *thisGame)
{
printf("%i, %i, %c", thisGame.variable, thisGame.number, thisGame.letter);
}
process.h:
#ifndef _MAIN_H_
#define _MAIN_H_
void displayData(Game *thisGame);
#endif
Error message
-------------- Build: Debug in FishKiller (compiler: GNU GCC Compiler)---------------
mingw32-g++.exe -L..\deps\lib -L..\SDLFILES\lib -o bin\Debug\FishKiller.exe obj\Debug\main.o obj\Debug\process.o -lmingw32 -lSDL2main -lSDL2 -lSDL2_image
obj\Debug\process.o:process.c:(.rdata+0x0): multiple definition of `SCREEN_WIDTH'
obj\Debug\main.o:main.c:(.rdata+0x0): first defined here
obj\Debug\process.o:process.c:(.rdata+0x4): multiple definition of `SCREEN_HEIGHT'
obj\Debug\main.o:main.c:(.rdata+0x4): first defined here
obj\Debug\process.o:process.c:(.rdata+0x8): multiple definition of `GAMESTATE_MENU'
obj\Debug\main.o:main.c:(.rdata+0x8): first defined here
obj\Debug\process.o:process.c:(.rdata+0xc): multiple definition of `GAMESTATE_GAME'
obj\Debug\main.o:main.c:(.rdata+0xc): first defined here
obj\Debug\process.o:process.c:(.rdata+0x10): multiple definition of `GAMESTATE_GAMEOVER'
obj\Debug\main.o:main.c:(.rdata+0x10): first defined here
collect2.exe: error: ld returned 1 exit status
Process terminated with status 1 (0 minute(s), 0 second(s))
0 error(s), 0 warning(s) (0 minute(s), 0 second(s))
Issues are address file by file below. Once these issues are corrected in your source, the executable will build.
1)
In process.h you have the wrong header blocks:
#ifndef _MAIN_H_
#define _MAIN_H_
//Change to:
#ifndef _PROCESS_H_
#define _PROCESS_H_
Also change:
void displayData(Game *thisGame);(see notes in main.h for explanation)
To:
void displayData(GAME *thisGame);
2) In process.c you have;
#include "main.h"
It does not hurt anything, but since we are analyzing everything, it is not needed to support current architecture.
You also have:
printf("%i, %i, %c", thisGame.variable, thisGame.number, thisGame.letter);
Because the thisGame is passed in as a pointer, you need to use struct pointer operator: ->
printf("%i, %i, %c", thisGame->variable, thisGame->number, thisGame->letter);
Also, the function protocol in the same file is incorrect. You are attempting to instantiate a variable type that does not exist: (see notes for main.h)
Change:
void displayData(Game *thisGame){...}
To:
void displayData(GAME *thisGame){...}//uses typedef struct GAME
3) in main.h you have a malformed struct:
typedef struct
{
int variable, number;
char letter;
}//no ";" statement terminator to indicate to your compiler _end of struct_
And with this definition, there is no struct name with which to reference or instantiate it in any other file. Change it to the following:
typedef struct
{
int variable;
int number;//style point , put each member on its own line
char letter;
}GAME;//note struct type name and terminator ";"
With the struct type name, in this case GAME, you can create instances of this struct in any file that #includes this file.
extern GAME Game;// using the extern modifier, create an instance of GAME
// that can be referenced in any file of the
//project, once initialized. (See the line GAME Game; in main.c)
4) in main.c you have variables in the function initGame that need to be referenced differently. Change this:
void initGame(Game *thisGame)
{
variable = 10;
number = 5;
letter = 'c';
}
To:
void initGame(GAME *thisGame)
{
thisGame->variable = 10;
thisGame->number = 5;
thisGame->letter = 'c';
}
There is Code::Blocks information here that may help you to set up your environment to get the error messages that will help you to debug your code.

stat.h file access file descriptors open() Hacking The Art of Exploitation

I am working out of the 2nd edition of Jon Erickson's "Hacking: The Art of Exploitation" using a VM (virutalbox) to run the LiveCD it came with (Ubuntu 7.04). In section 0x281 "File Access", the author explains accessing files through file descriptors, as well as the open() close() read() and write() functions, using an example on pages 82-84.
The code for the simplenote.c is as follows:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <fcntl.h>
#include <sys/stat.h>
void usage(char *prog_name,char *filename){
printf("Usage: %s < data to add to %s>\n",prog_name,filename);
exit(0);
}
void fatal(char *);
void *ec_malloc(unsigned int );
int main(int argc,char *argv[]){
int fd; //file descriptor
char *buffer,*datafile;
buffer = (char *)ec_malloc(100);
datafile = (char *)ec_malloc(20);
strcpy(datafile,"/tmp/notes");
if(argc < 2)
usage(argv[0],datafile);
strcpy(buffer,argv[1]);
printf("[DEBUG] buffer # %p:\'%s'\n",buffer,buffer);
printf("[DEBUG] datafile # %p:\'%s'\n",datafile,datafile);
strncat(buffer,"\n",1);//Add a newline on the end.
fd = open(datafile,O_WRONLY|O_CREAT|O_APPEND,S_IRUSR|S_IWUSR);
if(fd == -1)
fatal("in main() while opening file");
printf("[DEBUG] file descriptor is %d\n",fd);
//Writing data
if(write(fd,buffer,strlen(buffer)) == -1)
fatal("in main() while writing buffer to file");
//Closing file
if(close(fd) == -1)
fatal("in main() while closing file");
printf("Note has been saved.\n");
free(buffer);
free(datafile);
}
//A function to display an error message and then exit
void fatal(char *message){
char error_message[100];
strcpy(error_message,"[!!]Fatal Error");
strncat(error_message,message,83);
perror(error_message);
exit(-1);
}
//An error-checked malloc() wrapper function
void *ec_malloc(unsigned int size){
void *ptr;
ptr = malloc(size);
if(ptr == NULL)
fatal("in ec_malloc() on memory allocation");
return ptr;
}
However, when I type the following instructions stated in the book into my terminal window, it returns the following error message:
reader#hacking:~/booksrc $ gcc -o simplenote simplenote.c
In file included from /usr/include/sys/stat.h:105, from simplenote.c:6:
/usr/include/bits/stat.h:70: error: field 'st_atim' has incomplete type
/usr/include/bits/stat.h:71: error: field 'st_mtim' has incomplete type
/usr/include/bits/stat.h:72: error: field 'st_ctim' has incomplete type
simplenote.c: In function 'main':
simplenote.c:35: error: 'O-WRONLY' undeclared (first use in this function)
simplenote.c:35: error: (Each undeclared identifier is reported only once
simplenote.c:35: error: for each function it appears in.)
simplenote.c:35: error: 'O_CREAT' undeclared (first use in this function)
simplenote.c:35: error: 'O_APPEND' undeclared (first use in this function)
Here is sys/stat.h line 105:
#include <bits/stat.h>
And here is bits/stat.h lines 63-83:
#ifdef __USE_MISC
/* Nanosecond resolution timestamps are stored in a format
equivalent to 'struct timespec'. This is the type used
whenever possible but the Unix namespace rules do not allow the
identifier 'timespec' to appear in the <sys/stat.h> header.
Therefore we have to handle the use of this header in strictly
standard-compliant sources special. */
struct timespec st_atim; /* Time of last access. */
struct timespec st_mtim; /* Time of last modification. */
struct timespec st_ctim; /* Time of last status change. */
# define st_atime st_atim.tv_sec /* Backward compatibility */
# define st_mtime st_mtim.tv_sec
# define st_ctime st_ctim.tv_sec
#else
__time_t st_atime; /* Time of last access. */
unsigned long int st_atimensec; /* Nscecs of last access. */
__time_t st_mtime; /* Time of last modification. */
unsigned long int st_mtimensec; /* Nsecs of last modification. */
__time_t st_ctime; /* Time of last status change. */
unsigned long int st_ctimensec; /* Nsecs of last status change. */
#endif
I suppose this might be of some use for the first set of issues:
C++ system file bits/stat.h suddenly breaks with "error: field ‘st_atim’ has incomplete type"
/usr/include/time.h
cat time.h
doesn't do anything in my terminal window.
And here is the simplenote.c main function lines 1-6, 34-35:
#include <stdio.h>
#include <stdint.h>
#include <stdlib.h>
#include <string.h>
#include <fcntl.h>
#include <sys/stat.h>
// Opening the file
fd = open(datafile, O_WRONLY|O_CREAT|O_APPEND, S_IRUSR|S_IWUSR);
I'm guessing the open function problems stem from fcntl.h ?
I seem to keep running into issues because of faulty code the author provided. I don't want to constantly depend on the stackoverflow community for help, so what suggestions do you have for a novice about examining and fixing these problems in the future?
Thanks.
Transferring a selection of comments into a semi-coherent answer.
You should probably explicitly enable POSIX definitions. Add -D_XOPEN_SOURCE=700 to the command line, or #define _XOPEN_SOURCE 700 before the first #include and see if that solves anything. You should not be running into the problem though; the header should be self-contained.
Oh, but Ubuntu 7.04 is archaic…you may need to use 600 instead of 700. When was it released (when was the book published)? If it was 2009 or before, you probably need the older version (600). It's still surprising that you're seeing the error. The command line you specify doesn't contain the options that normally cause trouble (-ansi -pedantic, for example, or -std=c99 -pedantic). You could try using -std=gnu99 too; it might work better.
You had a similar problem recently (gcc -o stdlib.h syntax error c Hacking the Art of Exploitation). Did you get that resolved? It sounds as if the compilation system on the Live CD is not self-coherent, or the way you're able to use it means that it is not behaving self-coherently. Are you sure the compilation system works? It appears to be semi-defunct. Is it using the wrong headers, somehow?
I was able to resolve the previous problem by inserting #include <stdint.h> before #include <stdlib.h>
I will try the -D_XOPEN_SOURCE=600 and get back to you. Something must be wrong with the compilation system.
Well, you might need to include <time.h> (or possibly <sys/time.h>) before <sys/stat.h>, but the <sys/stat.h> header is broken if that works. And the <stdlib.h> header is broken if you have to include <stdint.h> before including it. I suppose Ubuntu 7.04 could be so old that you're supposed to #include <sys/types.h> before many of these headers, but that's still not an excuse for <stdlib.h>; that should be self-contained. POSIX 1997 required #include <sys/types.h> before <sys/stat.h>; POSIX 2004 did not. And I don't think Ubuntu 7.04 is quite that old.
Note, though, that the st_atim member is new; it was added to POSIX 2008 (and hence is in POSIX 2013). It was just st_atime before (and st_atime is now a macro for st_atim.tv_sec).
Including the -D_XOPEN_SOURCE=600 dealt with the bits stat issue. Ubuntu 7.04 was released in 2007 and the 2nd edition of the book that I am using came out in 2008. Also, not sure if this is of use, but in another previous example that included both <stdio.h> and <string.h> (as opposed to only <stdio.h>), the code would run fine without any intervention.
Interesting…it is going to make life interesting for you, in a way that life should not need to be interesting. (Chinese curses like "May you live in interesting times" spring to mind.) Use the -DXOPEN_SOURCE=600 option in all your compilations and keep your fingers crossed; that may well resolve most of your problems. Consider using -std=gnu99 as well, or instead. With luck, either or both of those should get you around most problems.
In case someone else is having the same issue with this book, I downloaded the iso file from hacking-live-1.0.iso.
Created a bootable usb and all works just fine without corrupted headers or anything.

c - implicit declaration of functions

This is my header file, tree.h
#ifndef TREE_H_
#define TREE_H_
#if defined treeItem
extern int totalnode;
treeItem *addItem(treeItem *node, char *w);
void printInOrder(treeItem *node, FILE *output);
void freeTree(treeItem *node);
#endif
#endif
This is the main() in main.c which include tree.h
#include <stdio.h>
#include <ctype.h>
#include <string.h>
#include <stdlib.h>
#include "tree.h"
#define MAX 1024
extern int totalnode;
int main(int argc, char *argv[]){
FILE *input;
FILE *output;
char *filename;
char ch[MAX];
//extern int totalnode;
struct treeItem *element;
element = NULL;
int i;
if (argc > 2){
output = fopen(argv[1], "w");
for(i = 2; i < argc + 1; i++){
filename = argv[i];
input = fopen(filename, "r");
if(input != NULL){
while(getword(ch, MAX, input) != EOF)
if (isalpha(ch[0]))
element = addItem(element, ch);
}
}
printInOrder(element, output);
fprintf(output,"-------------- \n ");
fprintf(output,"%4d Total number of different words",totalnode);
freeTree(element);
fclose(input);
fclose(output);
}
else{
printf("There is no input file.\n");
}
return 0;
}
compiler says:
../main.c: In function 'main':
../main.c:57: warning: implicit declaration of function 'addItem'
../main.c:57: warning: assignment makes pointer from integer without a cast
../main.c:60: warning: implicit declaration of function 'printInOrder'
../main.c:64: warning: implicit declaration of function 'freeTree'
another error: Undefined symbols for architecture x86_64:
"_totalnode", referenced from:
_main in main.o
_addItem in tree.o
ld: symbol(s) not found for architecture x86_64
collect2: ld returned 1 exit status
If I put all code in the same .c file without using header file, it works. But for now, it doesn't work. How can I fix it?
The line
#if defined treeItem
and the matching #endif should be removed from tree.h
Remember that preprocessing occurs conceptually before (or as the very first step of) the real compilation.
In general, you could have obtained the preprocessed form of main.c with
gcc -C -E main.c > main.i
and then look (e.g. with a pager like less) inside main.i
I often remove the generated preprocessor directives with
gcc -C -E main.c | grep -v '^#' > main.i
gcc -Wall -c main.i
this gives error messages with line numbers referring inside main.i (not main.c or tree.h) which is sometimes useful to debug macros. Another useful option to gcc is -H: it shows every #include-d file
In order to use the tree.h file 'as-is', and have it define items as you expect, you will have to define treeItem:
#include <stdio.h>
#include <ctype.h>
#include <string.h>
#include <stdlib.h>
/* You will need to define 'treeItem' prior to including 'tree.h'. */
typedef /* the defintition here */ treeItem;
#include "tree.h"
#define MAX 1024
extern int totalnode;
If you have the liberty of editing the tree.h file, it would probably be better to remove the line:
#if defined treeItem
and one of the lines:
#endif
Because you have pre compiler directives which exclude the substantive body of tree.h unless treeItem is defined, you must #define treeItem prior to the inclusion of tree.h within main.c, this is due to the way that precompiler directives are processed. This will solve the immediate problem.
I see that in main.c you have the line: struct treeItem *element;
If I am interpreting correctly that you intended this to satisfy the #ifdef treeItem line in your header, then you are misunderstanding how these # lines are like a separate language to C/C++. These lines are called precompiler directives, or more casually macros. Macros are commands for the preprocesser which operates over text files prior to compilation, for the purposes of creating in memory a full source code that can be compiled into an object that can later be linked with others to form your program. The preprocessor's defines are different from definitions in C/C++, and they don't directly interact. This line about the struct is practically invisible to the preprocessor, it knows nothing about C/C++. You must define this treeItem using #define, prior to the #ifdef.
More aesthetically, your header file should not guard like this, because it is superfluous. The main.c module's #include "tree.h" line alone is enough to indicate the intention of including the substantive body of tree.h. You have an appropriate guard against repeated inclusions, but the second guard regarding the treeItem definition seems unnecessary and is the cause of this issue. This latter paragraph is simply reiterating what other's have said, and would be technically superfluous as well if it does not contribute to persuading you of this opinion, however avoiding hypocrisy the first paragraph is a solution to your issue that does not intrude on your decision regarding said opinion.

Code compiles on AIX 5.3 but not AIX 7.1 something to do with struct shl_descriptor where is this defined?

I have some code that looks similar to the following:
#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <sys/errno.h>
#include <fcntl.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <errno.h>
#include <stdarg.h>
#include <sys/ldr.h>
int main (int argc, char **argv)
{
int liRC = 0;
struct shl_descriptor *lstModDesc;
int liEach;
char lsBaseName[513];
char *lsTheName;
for( liEach = 0; liRC == 0; liEach++ )
{
liRC = shl_get( liEach, &lstModDesc );
if( liRC == 0 )
{
strcpy( lsBaseName, lstModDesc->filename );
lsTheName = (char *)basename( lsBaseName );
/* do more stuff */
}
}
return 0;
}
What it is doing is enumerating all the shared libraries attached to the binary. This compiles fine on AIX 5.3 but on AIX 7.1 I am getting the following concerning lstModDesc:
"modulename.c", line 2553.30: 1506-285
(S) The indirection operator cannot be
a pplied to a pointer to an incomplete
struct or union.
I cannot find where shl_get is defined on my aix 5.3 box nor can I find where struct shl_descriptor is defined either. I am stumped. I even tried outputing the preprocessed output with the -E flag to the compiler with no luck. I did a recursive grep in /usr/include. Is there somewhere else I should be searching? Where are those definitions?
Are you sure that bit of the code was included in the compilation on AIX 5.3? I just went Google-whacking with 'site:ibm.com shl_descriptor' and there is precisely one item found:
http://www-01.ibm.com/support/docview.wss?uid=swg21212239
It is pointing to a problem on HP-UX with WAS (WebSphere Application Server). There is sample code which uses <dl.h> (dynamic loader), and shows shl_descriptor and shl_gethandle() and shl_load().
Given the complete absence of hits for anything in AIX and the presence of the HP-UX platform, then you have a slightly different problem to resolve. The question is:
Why is the conditional compilation on AIX 5.3 excluding the section that uses shl_descriptor and not excluding it on AIX 7.1. You should look at the conditions wrapped around that code in the #ifdef line, and see what is used to trigger the HP-only compilation on AIX 5.3.

Resources