2

I one of my assignment, I have a task to print the below whole structure in a string format.

Struct test
{
    int a,
    char char1,char2;
}

output should be: Structure is a=10,char1=b,char2=c; I know it is very simple by using

printf("Structure is a=%d,char1=%c, char2= %c", s.a,s.char1,s.char2);

But in real-time, I have a lot of big structures and I cannot write printf statements with access specifiers for each element of structure. Is there any other way to print the whole structure with just specifying the structure variable or some other?

4
  • 6
    No. There isn't a way to simply print the whole structure without having code that knows how to print it. Commented Mar 26, 2013 at 17:40
  • 3
    C doesn't have reflection, which is what you'd normally use to support such a thing. Depending on the situation, you may be able to simulate it with the preprocessor, or by using platform-specific code along with debug information. Commented Mar 26, 2013 at 17:41
  • @JonathanLeffler Technically, you could - if you knew the size, you could simply get the memory address of the Struct and then dump out the next n bytes of memory. It wouldn't be very useful, though. Commented Mar 26, 2013 at 17:42
  • If you write a declaration parser and if you know how structure/union members are aligned, you could feed it a pointer to a structure along with the textual representation of the structure type (can be simplified with macros) and have the structure printed properly. But that's not going to be easy. Commented Mar 26, 2013 at 22:16

2 Answers 2

6

There's no way to do this in pure C. Some languages support this via a concept called reflection, but it's not available in C.

Code-that-writes-code is your best bet. Write a script that finds all your structs and builds functions to printf them.

Sign up to request clarification or add additional context in comments.

Comments

-1

One possible solution I can think of is that you can take the help of the fread funtion using which you can save the whole content of the structure at once into a, say temporary file. Using:

fread(&STRUCTURE_OBJECT, sizeof(YOUR_STRUCTURE), 1, FILE_POINTER);

Where STRUCTURE_OBJECT is the name of a data element of your strucure. And then use linux based commands like "cat" and "piping" etc for the quick glance of the output.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.