Question

Using fgetc() and/or read() how to i get the keys and the values from a file? This is how it is written in the file:

 <key1,val1><key2,val2><key3,val3>

And i need to put each key and value in a new array(to do linked-lists).

So, to insert in the file using '<' and '>' and ',' it's no problem. The problem is how to get them? Any ideas?

Here's what I have.

FILE * file;
char* key;
char* value;
int c;//apparently I have to use an int
file=fopen("myfile.txt", "r");
c=fgetc(file);
while(c != EOF)
{
   c=fgetc(file);
   if(c == '<'){
      for(int i=0; c != ','; i++)
      {
         key[i]=fgetc(file);
      }
   }
}

This is till the first comma. Now I lack a little of algorithm conception. Help please.

Was it helpful?

Solution

Does it have to be fgetc and read ? .. Here is one way to do this :

     while(!feof(your_file_name)){
        bzero(line, sizeof(line)); // line is a char array ... make sure its of sufficiently large size
        fgets(line,100,your_file_name); // I am reading 100 characters  .. you can change that number as per your file accordingly
     }

    fclose(your_file_name);

    sscanf(line,"<%d,%d><%d,%d><%d,%d>",&key1,&val1,&key2,&val2,&key3,&val3); //  assuming keys and vals are ints

What you are doing in your code is reading the file character by character .. Why go through all that pain?

using fgets will read the entire file in one go ... then knowing the format of the file sscanf is immensely powerful tool to recover info from that


Ok so you posted in comments that keys and vals are strings .. so change the sscanf to this:

sscanf(line,"<%[^,]%[^>]<%[^,]%[^>]<%[^,]%[^>]",key1,val1,key2,val2,key3,val3);

Ok so let me explain

When dealing with the strings in sscanf you have to specify the delimiting character.

So this <%[^,] tells sscanf - start reading a string from after this < character and read it until you reach , character ...

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top