开发者

Read a file until a character in C

开发者 https://www.devze.com 2022-12-27 11:35 出处:网络
Say I have a file with the format: key1/value1 key2/value2 key3/value3 .... Say I have an array to hold these values:

Say I have a file with the format:

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

Say I have an array to hold these values:

char *data[10][10]

How would I read this file and get key1, key2, and key3 into data[0][0], data[1][0], and data[2][0]. Then put value1, value2, and value3 into data[0][1], data[2][1], and data[3][1]. So actually I want to get the strings of key1-key3 individually, then test for the '/' character then get the strings of value1-3. By the way, when I'm inputting these into the file, I am including the '\n' character 开发者_如何学运维so you could test for that to test for the newline.


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消