strtok with while loops


 
Thread Tools Search this Thread
Top Forums Programming strtok with while loops
# 1  
Old 02-07-2010
strtok with while loops

Why is line (null) after the first while loop run? (keyword does jump to the next word.)

Code:
#include <ftw.h>
#include <stdio.h>
#include <string.h>

char filenames[50000] = "";

int list(const char *name, const struct stat *status, int type)
{
    if( (type == FTW_F) && strstr(name, ".txt") && !strstr(name, ".c") )
    {
        sprintf(filenames + strlen(filenames), "%s,", name);
     }

    return 0;
}

int main(void)
{
    ftw("/path-to-directory", list, 1); // recursively buffer file names in directory

    char input[25] = "keyword1+keyword2+"; // no buffer overflow here...

    char filecontent[50000] = ""; // I checked, only about 25000 chars are used
    char filematches[50000] = "";

    size_t length = 0;

    FILE *file1;

    const char *line = strtok(filenames, ","); // file names separated by commas
    const char *keyword = strtok(searchstring, "+"); // key words separated by plus signs
    while(line != NULL)
    {
        file1 = fopen(line, "r");
        if (file1 != NULL)
        {
                length = fread(filecontent, 1, 49999, file1);
                fclose(file1); 
       }else{
            printf("fopen failed at: %s", line);
            exit(1);
        }

        filecontent[length] = '\0';

        while(keyword != NULL)
        {
            if(strstr(filecontent, keyword))
            {
                sprintf(filematches + strlen(filematches), "%s\n", line); // buffer file names that include at least one keyword
                break; // one keyword is in the file, no need to check for more
            }
            keyword = strtok(NULL, "+");
        }

        filecontent[0] = '\0';
        keyword = strtok(searchstring, "+"); // restart strtok to beginning of searchstring
        line = strtok(NULL, ","); // this is (null) after first run
    }
printf("filematches: %s\n", filematches);
    return 0;
}

# 2  
Old 02-07-2010
strtok works on the original string, and changes it so it cannot be used for other purposes.

Code:
#include <string.h>
#include <stdlib.h>
#define SZ 128  // fix this for your needs
static char hold[SZ];

char **foo( char **dest, const char *src, int *elems, const char *delims)
{
    int i=0;
    char *p=NULL;
    
    dest[0]=NULL;
    strcpy(hold, src);
    p=strtok(hold, delims);
    while(p!=NULL)
    {
       dest[i++]=p;
       dest[i]=NULL;
       p=strtok(NULL, delims);       
    }
    *elems=i;
    return dest;
}

you are not calling ftw() correctly either
# 3  
Old 02-07-2010
What is wrong about ftw() ? It works...
# 4  
Old 02-08-2010
Question

Wouldn't you avoid the strok completely with the following

Code:
#include <ftw.h>
#include <stdio.h>
#include <errno.h>
#include <string.h>

char filenames[500][256]; // use your local file length limit
int  filecount = 0;

int list(const char *name, const struct stat *status, int type)
{
  if( (type == FTW_F) && strstr(name, ".txt") && !strstr(name, ".c") )
  {
    snprintf (filenames[filecount], 255, "%s", name);
    filecount++;
  }

  return 0;
}

int main(void)
{ 
  // recursively buffer file names in directory
  if ( 0 != ftw ("/path-to-directory", list, 1) )
  {
    fprintf (stderr, "error in ftw: %s\n", strerror (errno));
    return (-1);
  }

  
  for ( int i = 0; i < filecount; i++ )
  {
    printf ("%3d :  %s\n", i, filenames[i]);
  }

  return 0;
}

Much easier to read, IMHO.
Login or Register to Ask a Question

Previous Thread | Next Thread

10 More Discussions You Might Find Interesting

1. Homework & Coursework Questions

If and Loops

Use and complete the template provided. The entire template must be completed. If you don't, your post may be deleted! 1. The problem statement, all variables and given/known data: In this script you will take a directory as input from the user and change the end of line sequence from a Unix... (1 Reply)
Discussion started by: Pcarson
1 Replies

2. Programming

strtok() gives segmentation fault!!

#include<iostream.h> #include<string> #include<stdio.h> int main() { char *cmd="delete backup backup-iso image a.iso b.iso c.iso d.iso"; char *tokenized_cmd,*sub_cmd; sub_cmd=strstr(cmd,"image"); tokenized_cmd=strtok(sub_cmd," "); ... (3 Replies)
Discussion started by: ashwini.engr07
3 Replies

3. Shell Programming and Scripting

Loops

Hi All, I am very new to Shell scripting. I read basic scripting manual. But i didn't understand the code. Please tell the meaning of the below code: while getopts "F:f:R:r:C:c:" opt 2>/dev/null do case ${opt} in F|f) FREQUENCY_MODE=$OPTARG;; ... (3 Replies)
Discussion started by: pdathu
3 Replies

4. Programming

How to use strtok twice in the same program?

string str1(" 1 2 3 4 512543 "); string str2; if(str2.empty()) str2=str1; cout << "str2:" <<str2 <<endl; p1=strtok((char *)str1.c_str()," "); while(p1) { ... (3 Replies)
Discussion started by: sathishkmrv
3 Replies

5. Shell Programming and Scripting

strtok equivalent in perl

Hi All, Is their any equivalent for strtok (in c) to use in perl script. Thanks in advance. JS (1 Reply)
Discussion started by: jisha
1 Replies

6. Programming

Regardign strtok() output directing to 2-D string array

Hi, I just wrote a program in C to split a comma seperated string in to group of strings using strtok() function. The code is: int main() { char *temp;//not used here but basically we extract one string after another using strtok() and assign to a string pointer defined like this. ... (3 Replies)
Discussion started by: SankarV
3 Replies

7. Linux

Strtok function....

can any help me out y dis program is giving me a segmentation fault..... #include<stdio.h> #include<string.h> int main() { char *str="Tanvir/home/root/hello"; const char *d ="/"; char *ret; ret=strtok(str,d); if(ret==NULL) printf("NULL NULL"); else ... (3 Replies)
Discussion started by: Tanvirk
3 Replies

8. UNIX for Dummies Questions & Answers

two loops

Hi, how can I use "for" to have two loops : this is my script : for i in (A B C) do for j in (a b c) do echo $i$j done done #End I want to print out Aa Ab Ac .... But I have error message : syntax error at line 1 : `(' unexpected Many thanks before. How should I use "for" ?? (2 Replies)
Discussion started by: big123456
2 Replies

9. Programming

better way than strtok?

Hi all, Right now I'm using this but it seems to be a hack: if (prefix(arg, "mark=")) { for (markid = strtok(args,"="); markid; markid=strtok((char *)NULL, "=")) { basically the user passes "mark=ny" to the command. I want to be able to extract "ny" from that... (7 Replies)
Discussion started by: annie
7 Replies

10. UNIX for Dummies Questions & Answers

While Loops

I'm trying to create a loop that will prompt the user for 15 values, not forcing them to enter all 15. If the user enters through one or more of the prompts the null value needs to be converted to 0, otherwise set the parameter = to the value entered: ex. Please enter file no #1: 17920 ... (4 Replies)
Discussion started by: vdc
4 Replies
Login or Register to Ask a Question