J. Doe
J. Doe

Reputation: 23

strategy to fprintf into a file from a buffer but going to a new line after every 100 characters?

Is there any simple function or strategy that will help me fprintf onto a file from a buffer that I have while moving to the next line every 100 characters?

Upvotes: 2

Views: 248

Answers (2)

David Ranieri
David Ranieri

Reputation: 41036

A simple loop:

#include <stdio.h>

#define MAX_LINE 100

int main(void)
{    
    char str[10000];
    char *ptr = str;
    int size;

    fgets(ptr, sizeof str, stdin);
    do {
        /* write a maximum of 100 chars to file and a trailing new line */
        /* size stores the number of chars written - trailing nl */
        size = fprintf(stdout, "%.*s\n", MAX_LINE, ptr) - 1;
        /* increment the ptr size positions */
        ptr += size;
        /* if (end-of-buffer - size < 100) exit loop */
    } while (size >= MAX_LINE);
    return 0;
}

Upvotes: 2

chqrlie
chqrlie

Reputation: 144969

In the general case, not really: fprintf does not come with an automatic line wrapping facility.

But you can take advantage of fprintf's return value: the number of characters that were written. Updating a column count, you can output a linefeed every time you go past a certain value. If your fprintf chunks are small enough, the can be a good approximation of what you are trying to do. To properly compute the column count, you must take into account any linefeeds you may output as part of an fprintf function call.

Otherwise, you can snprintf to a buffer and search for spaces to break the line appropriately or even just break the line arbitrarily at 100 characters.

Another more general solution is to use popen() to pipe the output through a utility that would perform the kind of wrapping you want.

Upvotes: 3

Related Questions