Print a structure in a String format in C - c

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?

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.

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.

Related

What is the Best Way to Accomplish Homoiconicity in C for this Particular Application?

I am trying to make a complex number grapher in C which takes an expression from the command line and generates a .bmp file.
Here's how I currently have my parser set up:
Node *parser(const char *input); /* `input' is the command line input */
complex eval(Node *queue_head, complex variable_value);
The parser function takes in a string and returns a queue of tokens which each contain an enum representing the type of the value in the Node and a union containing the value. The eval function takes in a queue alongside a value and returns a complex number as the result. This function is called for each pixel when the actual graphing takes place.
This seems terribly inefficient to me, but I'm not sure of a better way of doing this. Some thoughts I've had are turning the inputted expression into a .c file and then compiling it into an object file and including the file all at runtime and just using the function like a normal C function, but the thought of this is abhorrent to me (I also don't know if this is feasible or even possible and I don't have a C compiler on-hand at the moment).
Is there any better way of accomplishing what I want to do in C, despite the language not being homoiconic?

Access a cell directly in .csv file using C programming

hey guys!
is there any way of directly accessing a cell in a .csv file format using C?
e.g. i want to sum up a column using C, how do i do it?
It's probably easiest to use the scanf-family for this, but it depends a little on how your data is organized. Let's say you have three columns of numeric data, and you want to sum up the third column, you could loop over a statement like this: (file is a FILE*, and is opened using fopen, and you loop until end of file is reached)
int n; fscanf(file, "%*d,%*d,%d", &n);
and sum up the ns. If you have other kinds of data in your file, you need to specify your format string accordingly. If different lines have different kinds of data, you'll probably need to search the string for separators instead and pick the third interval.
That said, it's probably easier not to use C at all, e.g. perl or awk will probably do a better job, :) but I suppose that's not an option.
If you have to use C: read the entire line to memory, go couting "," until you reach your desired column, read the value and sum it, go to next line.
When you reach your value, you can use sscanf to read it.
You might want to start by looking at RFC 4180: Common Format and MIME Type for Comma-Separated Values (CSV) Files, and then looking for implementations of the same. (Be aware though, that the notion of comma separated values predates the RFC and there are many implementations that do not comply with that document.)
I find:
ccsv
And not many others in plain c. There are quite a few c++ implementations, and most of the are probably readily adapted to c.

C library for parsing query strings?

I'm writing a C/CGI web application. Is there a library to parse a query string into something like a GHashTable? I could write my own but it certainly doesn't seem to be worth the effort to reinvent the wheel.
The uriparser library can parse query strings into key-value pairs.
If you're really writing C and the set of keys is known, you'd do much better to store the values in a struct instead of some bloated hash table. Have a static const table of:
key name
type (integer/string is probably sufficient)
offset in struct (using offsetof macro)
and use that to parse the query string and fill in the struct.
You may find usefull the ap_getword functions family from the Apache Portable Runtime (apr) library.
Most of the string parsing routines belong to the ap_getword* family, which together provide functionality similar to the Perl split() function. Each member of this family is able to extract a word from a string, splitting the text on delimiters such as whitespace or commas. Unlike Perl split(), in which the entire string is split at once and the pieces are returned in a list, the ap_getword* functions operate on one word at a time. The function returns the next word each time it's called and keeps track of where it's been by bumping up a pointer.
You may search google for "ap_getword(r->pool" "httpd.h" and find some relevant source code to learn from.

How to write dynamically allocated structure to file

I have a complex structure in a C program which has many members that are allocated memory, dynamically. How do I write this structure to a text / binary file? How will I be able to recreate the entire structure from the data read from the file.
struct parseinfo{
int varcount;
int termcount;
char **variables;
char **terminals;
char ***actions;
};
The members variables, terminals and actions are all dynamically allocated and I need to write this structure to a file so that I could reconstruct the structure later.
You must write to this structure Serialize and Deserialize functions, you can't write this structure to file as raw data because you have allocated pointers on a heap and this not make sense to save this values on file.
Short: Not in an automated way.
In essence, it depends highly on the semantics of your structure.
If the data fields inside specify the length of certain arraiys inside it,
you can reconstruct the struct.
But you have to be careful to "beleive" the values. (possible cause of stack overflow (nice word)) if you believe that there are 2^34 entries in an array.
But otherwise it is just going tru every member (pain)
You could search a little about ASN.1 and TLV-structs.
Here are some suggestions for binary serialization:
You can serialize a string either a la C (write the terminating '\0') or
by writing the size (say, an int) followed by the contents.
You can serialize an array of strings by writing the length of the array
followed by the strings.
If it's possible that you deserialize the file on a different
architecture (different int size, different endianness...), then take
care to carefully specify the binary format of the file. In such a case
you may want to take a look at the XDR serialiaztion standard.
For ASCII serialization, I like the JSON format.
The way I would suggest to do it is to think about what does it take to create the items in the first place?
When it comes to the char **variables; char **terminals; char **actions you're obviously going to have to figure out how to declare those and read them in but I don't think you can inject a /0 into a file (EOF character??)
How would you like to see it written to the file? Can you provide a sample output how you think it should be stored? Perhaps one item per line in a file? Does it need to be a binary file?

Simple C question

HI all. I am trying to make little program that reads data from file which has name of user and some data for that user. I am new on C , and how can i calculate this data for its user?line by line reading and adding each char in array? And how can I read line? is there any function?
And how can I use this each line users like object?I will make calculation for specific user.
You can use fgets to read a line at a time from the file.
Then you can parse the fields out and add them to an array or some other data structure. Just keep in mind if you use an array then you need to know ahead of time how many entries the file may contain - for example, no more than 1000. Otherwise you will need to use a data structure that can dynamically allocate memory such as a linked list, vector, etc.
Try this site, i often use it for reference.
http://www.cprogramming.com/tutorial/cfileio.html
Play around with file i/o and get use to the functions and then you will be able to make what you want.
Everything you need is in stdio.h. (Link is to a C++ website but the entire C i/o system is usable in C++; hence the documentation)

Resources