SIFE
SIFE

Reputation: 5695

How to put columns in file

I have a file and I want to insert data in it as columns like this:

Column size: 5spaces 5spaces 12 spaces

25100 23501 169247103621

But I still have this two conditions:

  1. If the string bigger then the column size, I eliminate the odd length from the string.
  2. If the string smaller then the column size, I fill the rest of string with spaces.

Ex1:

2510025 23501 169247103621

Become:

25100 23501 169247103621

Ex2:

25 23501 169247103621

Become:

25    23501 169247103621

I manged to get this in c with printf, but now I want print some format in a file.

#include <stdio.h>


int main(int argc, char **argv)
{
   char FMT[] = "%-5.5s %5s %-6.12s\n";
   FILE *hFile = NULL;
   char *string  = "freeifaddrss";
   char *string2 = "cards";
   char *string3 = "ifa_nextifa_next";
   printf(FMT, string, string2, string3);
   return 0;
}

Upvotes: 0

Views: 95

Answers (2)

Senthil
Senthil

Reputation: 106

Why don't you try ?

fp = fopen( "output.txt", "w" );
if( fp != NULL )
  fprintf( fp, "Hello %s\n", name );

Upvotes: 0

William Morris
William Morris

Reputation: 3684

To write to a file you can either redirect the output of your program, eg:

./prog > out.txt

or open a file in the program and write to that:

FILE *f = fopen(argv[1], "w");
if (f == NULL) {
     perror(argv[1]);
     exit(EXIT_FAILURE);
}
...
fprintf(f, FMT, string, string2, string3);

Call this with:

./prog out.txt

Upvotes: 2

Related Questions