Home > database >  How to print String output to a file?
How to print String output to a file?

Time:01-06

I´m trying to mod a little Program to write text from an Input window to textfile. I´m not very familiar with C and tested a little bit around.

void wr_wprintf(wr_window_t *window, wi_string_t *fmt, ...) {
        wi_string_t             *string;
        va_list                 ap;

        va_start(ap, fmt);
        string = wi_string_init_with_format_and_arguments(wi_string_alloc(), fmt, ap);
        va_end(ap);
        wr_wprint(window, string);

        FILE *fp;
        fp = fopen("/home/pi/test", "w");
        fprintf(fp, string);
        fclose(fp);

        wi_release(string);
}

The command wr_wprint(window, string); is the output of the text. As you can see I tried already something with fopen. But it did not write the text to file. The file is created but there is nothing inside.

CodePudding user response:

UPDATE

After getting access to the library repo being used, I found the definition of wi_string_t. It is part of the libwired submodule. From there, the definition of wi_string_t can be found in libwired/data/wi-string.c. The fact that it is defined inside a c file (traditionally) means your program does not know the contents of the struct. This means that wi_string_t* acts as an "opaque pointer". Since we must pretend not to know the contents of the struct, we must utilize the API functions defined in wi-string.h. I was able to find the following in there:

 93 WI_EXPORT wi_uinteger_t                     wi_string_length(wi_string_t *);
 94 WI_EXPORT const char *                      wi_string_cstring(wi_string_t *);
 95 WI_EXPORT char                              wi_string_character_at_index(wi_string_t *, wi_uinteger_t);

At line 94, we have the function wi_string_cstring. A function that returns a const char* to the data itself. This is exactly what we need.

The following should work for you, but I didn't compile the library to know for sure:

void wr_wprintf(wr_window_t *window, wi_string_t *fmt, ...) {
        wi_string_t             *string;
        va_list                 ap;

        va_start(ap, fmt);
       

        string = wi_string_init_with_format_and_arguments(wi_string_alloc(), fmt, ap);
        va_end(ap);
        wr_wprint(window, string);

        FILE *fp;
        fp = fopen("/home/pi/test", "w");
        if (fp == NULL) {
                // error handling
        } else {
                fputs(wi_string_cstring(string), fp);
                fclose(fp);
        }

        wi_release(string);
}
  •  Tags:  
  • c
  • Related