Combined function for fprintf and writing in c / C ++

In C / C ++, there is a write () function that allows me to write to a file or socket, I just pass it in the file descriptor). And there are fprintf () that let me do fprintf (myFile, "hello% d", name); but it only works for the file.

Is there any api that allows me to do both? that is, allow me to print formatting and switch between writing to a file or socket?

Thank.

+3
source share
5 answers

sprintf snprintf char *, write. FILE *, fileno. FILE *: fdopen, FILE * .

, POSIX dprintf, GNU libc dprintf , :

GNU, C POSIX. , . (, MacOS) , dprintf(), printf(), ,

void dprintf (int level, const char *format, ...);

( - stderr). , dprintf() ( dprintf) printf. , , , .

, libc , dprintf, -, .: -)

+3

: fdopen , FILE*, fprintf .

+4

C, POSIX-ish ( "write()" ), :

  • fdopen(), .
  • fileno(), .

You need to be careful to flush the file stream at the appropriate times before using the appropriate file descriptor.

+4
source

You can do something like this, maybe:

#include <stdarg.h>

int fdprintf(int fd, const char* fmt, ...) {
  char buffer[4096] = {0};
  int cc;
  va_list args;
  va_start(args, fmt);
  if ((cc = vsnprintf(buffer, 4096, fmt, args)) > 0) {
    write(fd, buffer, cc);
  }
  va_end(args);
  return cc;
}
0
source

summarizing tusbar's answer, and for it to work with visual studio, you can try the following codes: `

int fdprintf(int fd, const char* fmt, ...) {
    int cc;
    va_list args;
    va_start(args, fmt);
    int len   = _vscprintf(fmt,args) + 1;
    char* buffer = new char[len];
    buffer[len] = 0;
    if ((cc = vsprintf_s(buffer, len-1, fmt, args)) > 0) {
        write(fd, buffer, cc);
    }
    va_end(args);
    delete[] buffer;
    return cc;
}

`

0
source

Source: https://habr.com/ru/post/1735517/


All Articles