Using ftw() properly in c

6.9k Views Asked by At

I have the following in my code: (Coding in c)

    ftw(argv[2], parseFile, 100)  

argv[2] is a local directory path. For instance. argv[2] = "TestCases" and there is a testcases folder in the same directory as my .o file.

My understanding is that this should traverse the directory TestCases and send every file it finds to the function parseFile.

What actually happens is it simply sends my argument to the function parseFile and that is all. What am I doing wrong? How am I suppose to use this properly?

EDIT: This is parseFile:

int parseFile(const char * ftw_filePath,const struct stat * ptr, int flags){
    FILE * file;
    TokenizerT * currFile;
    char fileString[1000], * currWord, * fileName;

    fileName = strdup(ftw_filePath);

    if( fileName == NULL || strlen(fileName) <= 0){
        free(fileName);
        return -1;
    }
    printf("\n%s\n",fileName);
    if(strcmp(fileName,"-h")== 0){
        printf("To run this program(wordstats) type './wordstat.c' followed by a space followed by the file's directory location. (e.g. Desktop/CS211/Assignment1/test.txt )");
        free(fileName);
        return 1;
    }
    else{
        file=fopen(fileName,"r");
    }

    if(!file){
        fprintf(stderr,"Error: File Does not Exist in designated location. Please restart the program and try again.\n");
        free(fileName);
        return 0;
    }
    memset(fileString, '\0', 1000);

    while(fscanf(file,"%s", fileString) != EOF){ /* traverses the file line by line*/
            stringToLower(fileString);
            currFile = TKCreate("alphanum",fileString);

            while((currWord = TKGetNextToken(currFile)) != NULL) {

                insert_List(currWord, words,fileName);

            }
            free(currFile->delimiters);
            free(currFile->copied_string);

            free(currFile);
        memset(fileString, '\0', 1000);
    }

    fclose(file);
    free(fileName);
    return 1;
}

It will work if I input TestCases/big.txt for my argv[2] but not if I put TestCases

2

There are 2 best solutions below

0
On BEST ANSWER

As described in the man page, a non-zero return value from the function that ftw is calling tells ftw to stop running.

Your code has various return statements, but the only one that returns 0 is an error condition.

2
On

A properly designed C callback interface has a void* argument that you can use to pass arbitrary data from the surrounding code into the callback. [n]ftw does not have such an argument, so you're kinda up a creek.

If your compiler supports thread-local variables (the __thread storage specifier) you can use them instead of globals; this will work but is not really that much tidier than globals.

If your C library has the fts family of functions, use those instead. They are available on most modern Unixes (including Linux, OSX, and recent *BSD)