Search code examples
file-iofputs

Writing a file using c program in the format of table


I want to write a file in the format of table using c program. I am using fputs to write the file. My file looks like :

    [sl] [Name] [School] [add]
    1 ABC DEF Dav India
    2 XYZ LLL USA

But, I want output file to look like :

    [sl]    [name]     [school]    [add]
     1      ABC DEF     DAV        INDIA
     2      XYZ         LLL        USA

I want to know is there something like length specifier in fputs like in printf so that I can change format of the file.


Solution

  • I think what you are looking for is fprintf. Find out more about fprintf here. It is used exactly the same way as printf, except it writes to a file.

    EDIT

    If your string is stored in different variables, then use fprintf as follows :

    fprintf(fp,"%-15s %-15s %-15s %-15s", "string 1", "string 2", "string 3", "string 4");
    

    The number 15 is the fixed length that the string will use (You can change this based on the maximum string length you have or some other preference). The minus sign is for left Justified string.