Results 1 to 2 of 2

Thread: Need help with getline and strtok

  1. #1

    Default Need help with getline and strtok

    I'm doing a total conversion from the bash version of scanvirus. I can use a fixed buffer for getline or a variable buffer(current).

    This version reallocates the buffer every time it gets a new string. Then I need to use strtok break the string up to get at the fields. Problem is strtok alters the string that is allocated in getline. Also, I need to remove the new line in the last field from strtok.

    Need help with this structure, a better method to do this. Will this result in memory leaks?

    Code:
         struct stat file_stats;
    
         char VirusVaultFolder[] = "/var/log/VirusVault";
         char VirusFoundFolder[] = "/var/log/VirusVault/VirusFound";
         char VirusConfig[] = "/var/log/VirusVault/scanvirus.cfg";
         char VirusScanLog[] = "/var/log/VirusVault/VirusScanLog.txt";
         
         FILE *FilePtr;
         char *line = NULL;
         size_t len = 0;
         ssize_t nread;
         
         const char s[2] = " ";
         char *token;
    
         int File_Found, File_Folder, status;
    
         FilePtr = fopen(VirusConfig, "r");
         if (FilePtr == NULL)
         {
             perror("fopen: VirusConfig");
             exit(EXIT_FAILURE);
         }
    
         while ((nread = getline(&line, &len, FilePtr)) != -1)
         {
              if (strstr(line,"TimeStamp= ") != NULL)
              {          
                  /* get the first token */
                  token = strtok(line, s);
       
                   /* walk through other tokens */
                   while( token != NULL )
                   {
                      printf( "'%s'\n", token );
                      token = strtok(NULL, s);
                   }
                   break;
              }
              else
                 printf("%s", line); 
          }
    
         free(line);
         exit(EXIT_SUCCESS);

  2. #2

    Default Re: Need help with getline and strtok

    strtok alters the original string. Is there a function to convert to a string array without altering the original string length.

    I need to take this:

    'string1 string3 string4 string5'

    into this:

    element[0]='string1'
    element[1]='string2'
    element[2]='string3'

    I'm thinking about using a array of string pointers. Then scan the string for spaces converting them to '/0' characters. Then setting each ptr to the beginning of each string.

    string1[\0]string3[\0]string4[\0]string5
    ^ ^ ^ ^

Tags for this Thread

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •