The best method is to read the data per line into a buffer, then parse the buffer. This can be expanded to reading in large blocks of data.
Use fgets
for reading the data into a buffer.
Use strchr
to find the separator character.
Example:
#include <stdio.h>
#include <stdlib.h>
#define MAX_TEXT_LINE_LENGTH 128
int main(void)
{
FILE * my_file("data.txt", "r");
char text_read[MAX_TEXT_LINE_LENGTH];
char key_text[64];
char value_text[64];
if (!my_file)
{
fprintf(stderr, "Error opening data file: data.txt");
return EXIT_FAILURE;
}
while (fgets(text_read, MAX_TEXT_LINE_LENGTH, my_file))
{
char * p;
//----------------------------------------------
// Find the separator.
//----------------------------------------------
p = strchr('/');
key_text[0] = '\0';
value_text[0] = '\0';
if (p != 0)
{
size_t key_length = 0;
key_length = p - text_read;
// Skip over the separator
++p;
strcpy(value_text, p);
strncpy(key_text, text_read, key_length);
key_text[key_length] = '\0';
fprintf(stdout,
"Found, key: \"%s\", value: \"%s\"\n",
key_text,
value_text);
}
else
{
fprintf(stdout,
"Invalid formatted text: \"%s\"\n",
text_read);
}
} // End: while fgets
fclose(my_file);
return EXIT_SUCCESS;
}
Note: The above code has not been compiled nor tested, but is for illustrative purposes only.