Closed liyanrui closed 12 months ago
Unfortunately, no specific treatment is given. I am expecting two options
%s
copy data%@s
pointer (maybe, pass two values, one accepting the string length and the other accepting the string address)In fact, even if a width specifier is provided for %s
, it is still impossible to include whitespace
https://en.cppreference.com/w/c/io/fscanf
🤯
use %<number>c
The description of %c is very clear, but I didn't notice it
But it is a pity that the length variable is not supported.
I chose to directly write a function to implement it
char* _fy_node_get_string( struct fy_node* node, const char* name )
{
struct fy_node* s = fy_node_by_path( node, name, -1, FYNWF_DONT_FOLLOW );
if ( !fy_node_is_scalar( s ) )
return NULL;
size_t len = 0;
const char* str = fy_node_get_scalar( s, &len );
return g_strndup( str, len );
}
@q962 Thanks your tips. I slightly modified your code and made a full minimum example.
#include <stdio.h>
#include <stdlib.h>
#include <libfyaml.h>
char* get_string_from_node(struct fy_node* node, const char* name) {
struct fy_node* s = fy_node_by_path(node, name, -1, FYNWF_DONT_FOLLOW);
if (!fy_node_is_scalar(s))
return NULL;
size_t len = 0;
const char* str = fy_node_get_scalar(s, &len);
char *ret = malloc((len + 1) * sizeof(char));
strncpy(ret, str, len);
ret[len] = '\0';
return ret;
}
int main(void) {
struct fy_document *fyd = fy_document_build_from_file(NULL, "foo.yaml");
struct fy_node *root = fy_document_root(fyd);
char *s = get_string_from_node(root, "/text");
printf("%s\n", s);
free(s);
fy_document_destroy(fyd);
return 0;
}
Here is a minimum example.
foo.yaml:
foo.c:
This program outputs