You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

C语言:如何解析特定格式的文件(或字符串)

How to Implement an Attribute Lookup Function in C

Alright, let's work through this problem step by step. First, I’ll make a reasonable assumption about your file’s format since you didn’t specify: I’ll assume your content uses a simple key=value structure (like INI files, where each attribute is on its own line, with no extra spaces around the = unless they’re part of the value). If your actual format differs, we can tweak the logic, but this is a common, flexible starting point.

Function Requirements Recap

We need a function that:

  • Takes a char* of file content, a target attribute name, and a char* buffer to store the value
  • Returns 0 if the attribute is found, 1 if not
  • Avoids buffer overflows and handles edge cases gracefully

Implementation Code

Here’s a robust implementation with safety checks and clear logic:

#include <string.h>
#include <stdio.h>

int find_attribute(const char* file_content, const char* target_key, char* value, size_t value_max_len) {
    // Validate input parameters first to prevent crashes
    if (!file_content || !target_key || !value || value_max_len == 0) {
        fprintf(stderr, "Error: Invalid input parameters\n");
        return 1;
    }

    const char* current_line = file_content;
    const size_t target_key_length = strlen(target_key);

    // Iterate through each line of the content
    while (*current_line != '\0') {
        // Find the end of the current line (either newline or end of string)
        const char* line_end = strchr(current_line, '\n');
        if (!line_end) {
            line_end = current_line + strlen(current_line);
        }

        // Locate the equals sign that separates key and value
        const char* equals_pos = strchr(current_line, '=');
        if (equals_pos != NULL && equals_pos < line_end) {
            // Calculate length of the key in this line
            const size_t key_length = equals_pos - current_line;

            // Check if this key exactly matches our target
            if (key_length == target_key_length && strncmp(current_line, target_key, key_length) == 0) {
                // Extract the value part (after the equals sign)
                const char* value_start = equals_pos + 1;
                const size_t available_value_length = line_end - value_start;

                // Copy value to buffer, ensuring we don't overflow
                const size_t copy_length = (available_value_length < value_max_len - 1) 
                    ? available_value_length 
                    : (value_max_len - 1);
                
                strncpy(value, value_start, copy_length);
                value[copy_length] = '\0'; // Guarantee null-termination

                return 0; // Success: attribute found
            }
        }

        // Move to the next line
        current_line = line_end + 1;
    }

    // If we exit the loop, the attribute wasn't found
    return 1;
}

Key Details & Edge Cases Handled

  • Input Validation: We check for null pointers and invalid buffer sizes first to avoid undefined behavior.
  • Exact Key Matching: We compare both length and content to prevent partial matches (e.g., avoiding confusing "age" with "age_group").
  • Buffer Safety: Using strncpy and explicitly adding a null terminator ensures we never overflow the output buffer.
  • Last Line Handling: If the final attribute line doesn’t end with a newline, we still process it correctly.
  • Read-Only Content: The function uses const char* for the input content, so it never modifies the original data.

Example Usage

Test the function with sample content:

int main() {
    const char* sample_content = "username=jschlitt\nrole=developer\nlocation=New York";
    char value_buffer[256];

    // Look for an existing attribute
    int result = find_attribute(sample_content, "role", value_buffer, sizeof(value_buffer));
    if (result == 0) {
        printf("Found role: %s\n", value_buffer); // Output: Found role: developer
    } else {
        printf("Attribute not found\n");
    }

    // Look for a non-existent attribute
    result = find_attribute(sample_content, "phone", value_buffer, sizeof(value_buffer));
    if (result == 0) {
        printf("Found phone: %s\n", value_buffer);
    } else {
        printf("Attribute not found\n"); // Output: Attribute not found
    }

    return 0;
}

Customization Tips

  • If your format uses a different separator (like : instead of =), replace '=' in strchr(current_line, '=') with your separator.
  • If values can span multiple lines, you’ll need to adjust the logic to detect when a value continues (e.g., look for the next key start instead of stopping at newlines).
  • If keys/values are wrapped in quotes, add logic to strip those quotes when extracting the value.

内容的提问来源于stack exchange,提问作者Chris Schlitt

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.20 07:52:55