• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 169
  • Last Modified:

C\C++

Hi, I need to read text file,
format of file is following,
1234|ab||2342|sgas|
1234|ab|23|2342|sgas|
There is pipe delimeter, there may be data in between pipe or may not.
I have written following code,
---------------------------------------------------
if((fp = fopen(temp_filename,"r+")) == NULL)
      {
            printf("Errno = %d\n",errno);
            printf("file cannot be opened. ErrNo = %d \n",errno);
            return -1;
      }
      
      while(!feof(fp))
      {
            
            if(fgets(s_data,100,fp) != NULL)
            {
                  strcpy(var1,strtok(s_data,"|"));
                  strcpy(var2,strtok(NULL,"|"));
                  strcpy(var3,strtok(NULL,"|"));
                  strcpy(var4,strtok(NULL,"|"));
                  strcpy(var5,strtok(NULL,"|"));
                  
            }
            
      }
--------------------------------------------------------------------------------------------

but this doesnt seems to be working when any data is missing.

How can i handle this.
Please suggest.
Thanks in advance.
Abhi



0
vjabhi
Asked:
vjabhi
  • 3
1 Solution
 
Infinity08Commented:
>> but this doesnt seems to be working when any data is missing.

Yes, consecutive delimiters are treated as one delimiter by strtok.

You could write your own strtok function that doesn't do that. Something like :

    char *my_strtok(char *str, char *delimiters) {
        static char *cur = 0;
        char *ret = 0;
        if (str) cur = str;
        if (cur) {
            size_t token_len = strcspn(cur, delimiters);
            ret = cur;
            cur += token_len;
            if (*cur) {
                *cur++ = '\0';
            }
            else {
                cur = 0;
            }
        }
        return ret;
    }

This code is untested, but it should be ok ...
0
 
Infinity08Commented:
>> This code is untested, but it should be ok ...

just tested it too ;)
0
 
vjabhiAuthor Commented:
its working.
Thank you very much...
0
 
Infinity08Commented:
No problem ... glad to be of assistance :)
0

Featured Post

Upgrade your Question Security!

Add Premium security features to your question to ensure its privacy or anonymity. Learn more about your ability to control Question Security today.

  • 3
Tackle projects and never again get stuck behind a technical roadblock.
Join Now