The best way is to read the data in a row into a buffer, and then parse the buffer. It can be expanded to be read in large blocks of data.
Use fgets to read data into the buffer.
Use strchr to find the delimiter 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 or tested, but is for illustration only.
source share