Read the file before the character in C

Let's say I have a file with the format:

key1/value1 key2/value2 key3/value3 .... 

Let's say I have an array to store these values:

 char *data[10][10] 

How would I read this file and run key1, key2 and key3 into data [0] [0], data [1] [0] and data [2] [0]. Then put values1, value2 and value3 into data [0] [1], data [2] [1] and data [3] [1]. So actually I want to get the strings key1-key3 separately, and then check for the character '/', and then get strings of values ​​1-3. By the way, when I enter them into a file, I include the "\ n" character so that you can test it to check for a new line.

+4
source share
1 answer

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.

+5
source

Source: https://habr.com/ru/post/1306974/


All Articles