user3052323
user3052323

Reputation: 3

C read colon delimited text file

The code reads a text file delimited by colons : and formatted as follows

1111:2222:3333

How would I store the values separated by colons : into separate variables ?

any help would be appreciated.

program code:

#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
#include <string.h>

int read_file();

int main()
{

read_file(); // calls function to read file

return 0;

}

// read text file function
int read_file()
{
char line[100];
char file_location[40];

FILE *p_file;

printf("Enter file location: ");
scanf("%s",file_location);

p_file =fopen(file_location, "r");

if(!p_file)
{
    printf("\n File missing:");
    return 0;
}

while(fgets(line,100,p_file)!=NULL)
{
    printf("%s \n",line);
}

fclose(p_file);

return 0;
}

Upvotes: 0

Views: 3547

Answers (2)

jim mcnamara
jim mcnamara

Reputation: 16389

POW already gave you everything you need to know. So, FWIW: One of the things C coders do is to keep a library of simple utitlies. Whacking a string up using delimiters is one of those utilities.

Here is a very simple (no error checking) example:

char **split(char **r, char *w, const char *src, char *delim)
{
   int i=0;
   char *p=NULL;
   w=strdup(src);    // use w as the sacrificial string
   for(p=strtok(w, delim); p; p=strtok(NULL, delim)  )
   {
       r[i++]=p;
       r[i]=NULL;
   }
   return r;
}

int main()
{
   char test[164]={0x0};
   char *w=NULL;            // keep test whole; strtok() destroys its argument string
   char *r[10]={NULL};
   int i=0;
   strcpy(test,"1:2:3:4:hi there:5");
   split(r, w, test, ":\n");  // no \n wanted in last array element
   while(r[i]) printf("value='%s'\n", r[i++]); 
   printf("w='%s' test is ok='%s'\n", 
      (w==NULL)? "NULL" : w, test);// test is still usable
   free(w);                  // w is no longer needed
   return 0;
}

Upvotes: 1

P0W
P0W

Reputation: 47794

This will give you a hint :

Use strtok as you would do for reading a csv file

while(fgets(line,100,p_file) != NULL)
{
    char *p = strtok(line, ":");
    while(p)
    {
        printf("%s\n", p); //Store into array or variables
        p=strtok(NULL, ":");
    }
}

Upvotes: 2

Related Questions